<?php

namespace Api\Controller;

use Think\Controller;

class ServerController extends Controller {

    public function getOrderUsers(){
        $users = M("away_order")->field("distinct phone,realname,receive_id,count(id) as count,circles")->where("phone != ''")->order("circles")->group("phone")->select();
        $this->assign("users",$users);
        $this->display();
    }

    public function check_msg(){
        $id = $_REQUEST['id'];
        $res = 0;
        $order = M("away_order")->where("id=".$id)->field("realname,phone,memo,address")->find();
        if($order){
            if(!$order['realname'] || !$order['phone'] || !$order['address']){
                $res = 0;
            }else{
                $res = 1;
            }
        }
        $result = array('status'=>0,'msg'=>'请求成功','res'=>$res);
        echo json_encode($result);
        exit;
    }

    public function check_msg2(){
        $id = $_REQUEST['id'];
        $res = 0;
        $receive_id = M("away_order")->where("id=".$id)->getField("receive_id");
        if($receive_id){
            $res = 1;
        }else{
            $res = 0;
        }
        $result = array('status'=>0,'msg'=>'请求成功','res'=>$res);
        echo json_encode($result);
        exit;
    }

    public function add_order_shxx(){
        $oid = $_REQUEST['oid'];
        $data['phone'] = $_REQUEST['phone'];
        $data['address'] = $_REQUEST['address'];
        $data['memo'] = $_REQUEST['memo'];
        M("tuan_order")->where("id=".$oid)->save($data);
        $result = array('status'=>0,'msg'=>"添加成功");
        echo json_encode($result);
        exit;
    }

    public function add_away_order_shxx(){
        $oid = $_REQUEST['oid'];
        $data['realname'] = $_REQUEST['realname'];
        $data['phone'] = $_REQUEST['phone'];
        $data['address'] = $_REQUEST['address'];
        $data['memo'] = $_REQUEST['memo'];
        M("away_order")->where("id=".$oid)->save($data);
        $result = array('status'=>0,'msg'=>"添加成功");
        echo json_encode($result);
        exit;
    }

    public function update_order_coupon(){
        $order_id = $_REQUEST['order_id'];
        $coupon_id = $_REQUEST['coupon_id'];
        $flag = $_REQUEST['flag'];
        if($flag == "tuan"){
            $res = M("tuan_order")->where("id = ".$order_id)->save(array("coupon_id"=>$coupon_id));
        }
        if($flag == "away"){
            $res = M("away_order")->where("id = ".$order_id)->save(array("coupon_id"=>$coupon_id));
        }
        if($res){
            $result = array(
                'status'=>0,
                'msg'=>"修改成功"
            );
        }else{
            $result = array(
                'status'=>1,
                'msg'=>"修改失败"
            );
        }
        echo json_encode($result);
        exit;
    }

    public function order_detail(){
        $id = $_REQUEST['id'];
        $detail = M('tuan_order_goods g')->join('left join meal_tuan_order o on (g.order_id = o.id)')->field('o.id,o.order_sn,o.user_id,o.total_price,g.unit_price,g.amount,g.goods_name,o.status,o.order_time')->where('o.id='.$id)->find();
        $result = array(
            'status' => 0,
            'rows'=>$detail,
        );
        echo json_encode($result);
        exit;
    }

    public function add_order_memo(){
        $id = $_REQUEST['id'];
        $memo = $_REQUEST['memo'];
        M("away_order")->where("id=".$id)->save(array("memo"=>$memo));
        $result['status'] = 0;
        $result['msg'] = "请求成功";
        echo json_encode($result);
        exit;
    }

    public function checkMobile(){
        $mobile = $_REQUEST['mobile'];
        $count = M("user")->where("phone=".$mobile." and name != '' and (is_check = 1 or is_check = 2)")->count();
        echo json_encode(array('count'=>$count));
        exit;
    }

    public function getOrderDetail(){
        $id = $_REQUEST['id'];
        $detail = M('tuan_order_goods o')->join('meal_goods g on (o.goods_id=g.id)')->field('g.id,g.name,g.img,g.discount,g.price,g.intro,o.amount')->where('o.order_id='.$id)->find();
        $detail['intro'] = mb_substr($detail['intro'],0,25,'utf-8');
        echo json_encode($detail);
        exit;
    }

    public function getOrderDetail2(){
        $id = $_REQUEST['id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $order = M("tuan_order")->where("id = ".$id)->field("id,order_sn,total_price,order_time,status")->find();
            $order['s'] = strlen($order['order_sn']);
            if(!$order){
                $result['status'] = 1;
                $result['msg'] = "无此订单";
            }else{
                $dishes = M('tuan_order_goods o')->join('meal_goods g on (o.goods_id=g.id)')->field('g.id,g.name,g.img,g.discount,g.price,g.intro,o.amount')->where('o.order_id='.$id)->find();
                $order['dishes'] = $dishes;
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['order'] = $order;
            }
        }
        echo json_encode($result);
        exit;
    }

    public function getAwayOrderDetail(){
        $id = $_REQUEST['id'];
        $detail = M('away_order')->where('id='.$id)->find();
        $shop_ids = M("away_order_goods")->where("order_id = ".$id)->field("distinct shop_id")->select();
        $shops = array();
        foreach ($shop_ids as $shop_id) {
            $shop = M("shop")->where("id = ".$shop_id['shop_id'])->field("id,name,username,logo,intro")->find();
            $shop['dishes'] = M("away_order_goods g")->join("left join meal_shop_dishes d on (g.goods_id = d.id)")->where("g.shop_id = ".$shop_id['shop_id']." and g.order_id = ".$id)->field("d.id,d.name,g.unit_price as price,g.amount,(g.unit_price*g.amount) as total_price")->select();
            $shops[] = $shop;
        }
        $detail['shops'] = $shops;
        echo json_encode($detail);
        exit;
    }

    public function getAwayOrderDetail2(){
        $user_id = $_REQUEST['user_id'];
        $id = $_REQUEST['id'];
        $detail = M('away_order')->where('id='.$id)->find();
        if($detail['user_id'] == $user_id){
            $detail['is_own'] = 1;
        }else{
            $detail['is_own'] = 0;
        }
        $count = M("away_order")->where("order_id = ".$id." and user_id = ".$user_id)->count();
        if($count){
            $detail['is_order'] = 1;
        }else{
            $detail['is_order'] = 0;
        }
        $detail['num'] = M("away_order")->where("order_id = ".$id." and status > 1 and status < 4")->count();
        $detail['dishes'] = M("away_order_goods g")->join("left join meal_shop_dishes d on (g.goods_id = d.id) left join meal_dish_gg gg on (g.gg_id = gg.id)")->where("g.order_id = ".$id)->field("d.id,d.name,g.unit_price as price,g.amount,(g.unit_price*g.amount) as total_price,d.img,g.shop_id,gg.gg")->select();
        echo json_encode($detail);
        exit;
    }

    public function get_order_yzm(){
        $id = $_REQUEST['id'];
        $codes = M('tuan_order_code')->where('order_id='.$id)->select();
        echo json_encode($codes);
        exit;
    }

    public function get_away_order_yzm(){
        $id = $_REQUEST['id'];
        $code = M('away_order_code')->where('order_id='.$id)->find();
        echo json_encode($code);
        exit;
    }

    public function getAreaByid(){
        $id = $_REQUEST['id'];
        $name = M('area')->where('id='.$id)->getField('name');
        echo json_encode($name);
        exit;
    }

    public function getCats(){
        $id = $_REQUEST['id'];
        $cats = M('category')->where('pid='.$id." and is_check = 1")->order('ord desc')->select();
        echo json_encode($cats);
        exit;
    }

    public function getArea(){
        $id = $_REQUEST['id'];
        $areas = M('area')->where('pid = '.$id." and is_check = 1")->order('ord desc')->select();
        echo json_encode($areas);
        exit;
    }

    public function find_words(){
        $words = $_REQUEST['words'];
        $res = array();
        $cats = M("category")->where("name like '%".$words."%' and is_check=1")->order('ord desc')->field("name,id,pid")->select();
        $shops = M("shop")->where("name like '%".$words."%' and is_check=1")->limit(0,6)->order('ord desc')->field("name,id")->select();
        if($cats){
            foreach ($cats as &$cat) {
                if($cat['pid']){
                    $cat['count'] = M("goods g")->join("meal_shop s on (g.sid = s.id)")->where("g.sub_cat=".$cat['id']." and g.is_check=1 and s.is_check = 1")->count();
                }else{
                    $cat['count'] = M("goods g")->join("meal_shop s on (g.sid = s.id)")->where("g.p_cat=".$cat['id']." and g.is_check=1 and s.is_check = 1")->count();
                }
            }
        }
        if($shops){
            foreach ($shops as &$shop) {
                $shop['count'] = M("goods")->where("sid=".$shop['id']." and is_check=1")->count();
            }
        }
        $res['cats'] = $cats;
        $res['shops'] = $shops;
        echo json_encode($res);
        exit;
    }

    /*
     * @queyuan
     * 首页推荐商品
     * 2015-5-6
     */
    public function recommend_goods(){
        $x = $_REQUEST['x'];//经度（y）
        $y = $_REQUEST['y'];//纬度（x）
        $city_id = $_REQUEST['city_id'];
        $sql = "g.recommend = 1 and g.is_check = 1 and s.map_x != '' and s.map_y != '' and s.circles like '%,".$city_id.",%'";
        $field = "g.id,g.intro,g.discount,g.price,g.salenum,s.name,s.map_x,s.map_y,g.img,s.circles,s.min_discount,round(6378.138*2*asin(sqrt(pow(sin((".$x."*pi()/180-s.map_x*pi()/180)/2),2)+cos(".$x."*pi()/180)*cos(s.map_x*pi()/180)* pow(sin((".$y."*pi()/180-s.map_y*pi()/180)/2),2))),2) as dis,c.name as cat";
        $goods = M('goods g')->field($field)->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.sub_cat = c.id)")->order("g.ord desc")->limit(0,20)->where($sql)->select();
        echo json_encode($goods);
        exit;
    }

    public function recommend_goods2(){
        $city_id = $_REQUEST['city_id'];
        $sql = "g.recommend = 1 and g.is_check = 1 and s.map_x != '' and s.map_y != '' and s.circles like '%,".$city_id.",%'";
        $field = "g.id,g.intro,g.discount,g.price,g.salenum,s.name,s.map_x,s.map_y,g.img,s.circles,s.min_discount,c.name as cat";
        $goods = M('goods g')->field($field)->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.sub_cat = c.id)")->order("g.ord desc")->limit(0,2)->where($sql)->select();
        echo json_encode($goods);
        exit;
    }

    /**
     * 首页活动产品
     * @queyuan
     * 2016/05/03
     */
    public function index_active_dishes(){
        $id_fruit = $_REQUEST['id_fruit'];
        $id_veg = $_REQUEST['id_veg'];
        $type = $_REQUEST['type'];
        $result = array();
        if(!$id_fruit || !$id_veg || !$type){
            $result['status'] = 1;
            $result['msg'] = "参数错误";
        }else{
            $actives = M("active_dishes a")->join("left join meal_shop_dishes d on (a.dish_id = d.id) left join meal_shop s on (d.shop_id = s.id)")->where("s.id in (".$id_fruit.",".$id_veg.") and a.type in (".$type.") and a.deadline > ".time()." and a.status = 1")->field("a.id,a.name,a.ad_img,a.dish_id,a.type,a.begintime,a.deadline")->order("a.ord desc")->limit("0,3")->select();

            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['actives'] = $actives;
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取活动详情
     * @queyuan
     * 2016-05-04
     * @param id——活动ID
     */
    public function activeDetail(){
        $id = $_REQUEST['id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数错误";
        }else{
            $active = M("active_dishes a")->join("left join meal_shop_dishes d on (a.dish_id = d.id) left join meal_shop s on (d.shop_id = s.id) left join meal_dish_gg g on (g.active_id = a.id)")->where("a.id = ".$id." and a.status = 1")->field("a.id,a.name,d.img,d.detail_img,d.shop_id,a.dish_id,a.type,a.begintime,a.deadline,g.price,g.gg,g.id as gg_id,d.name as dish_name")->find();
            $active['price_min'] = M("dish_gg")->where("dish_id = ".$active['dish_id']." and status = 1 and active_id = 0")->getField("min(price)");
            if($active){
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['detail'] = $active;
            }else{
                $result['status'] = 1;
                $result['msg'] = "无此活动";
            }
        }
        echo json_encode($result);
        exit;
    }

    /*
     * @chenxuan
     * 团购列表
     * 2015-5-6
     */

    public function goods() {
        $attr = $_REQUEST['attr'];
        $cityid = $_REQUEST['cityid'];
        $circleid = $_REQUEST['circleid'];
        $cateid = $_REQUEST['cateid'];
        $sub_cateid = $_REQUEST['sub_cateid'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $recommend = $_REQUEST['recommend'];
        $ord = $_REQUEST['ord'];
        $where = "g.is_check=1 and s.is_check = 1";
        if ($recommend) {
            $where .= " and g.recommend = $recommend ";
        }
        if($cityid){
            $where .= " and s.circles like '%,".$cityid.",%'";
        }
        if($circleid){
            $where .= " and s.circles like '%,".$circleid."'";
        }
        if($cateid){
            $where .= " and g.p_cat = ".$cateid;
        }
        if($sub_cateid){
            $where .= " and g.sub_cat = ".$sub_cateid;
        }
        if($ord == 1){
            $order = "g.salenum desc,";
        }
        if($ord == 2){
            $order = "g.discount desc,";
        }
        if($ord == 3){
            $order = "g.discount asc,";
        }
        if (empty($pagesizes)) {
            $pagesizes = 20;
        }
        if (empty($startrow)) {
            $startrow = 0;
        }
        $count = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->where($where)->count();
        $nums = ceil($count/$pagesizes);
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesizes;
        $results = array();
        $results['status'] == '00';
        $results['data']['total'] = $count;
        $results['data']['startrow'] = $startrow;
        $results['data']['nums'] = $nums;
        if ($count > 0) {
            $lists = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->field("g.id,g.name,g.img,c.name as cate,ca.name as sub_cate,g.discount,g.price,g.salenum,g.valid_time,g.no_valid_time_start,g.no_valid_time_end,g.recommend,s.circles,s.addr,s.min_discount")->where($where)->limit($limit.",".$pagesizes)->order($order."g.ord,g.id desc")->select();
            foreach ($lists as &$val) {
                if($val['img']){
                    $img_array = explode(",",$val['img']);
                    if($img_array){
                        $val['img'] = C('SITE_URL') . C('goodsFile') . $img_array[0];
                    }
                }
            }
            $results['data']['rows'] = $lists;
        }else{
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    public function goods2() {
        $cityid = $_REQUEST['cityid'];
        $areaid = $_REQUEST['areaid'];
        $pid = $_REQUEST['pid'];
        $sub_id = $_REQUEST['sub_id'];
        $startrow = $_REQUEST['startrow'];
        $pagesize = $_REQUEST['pagesize'];
        $ord = $_REQUEST['ord'];
        $x = round($_REQUEST['x'],6);
        $y = round($_REQUEST['y'],6);
        $where = "g.is_check=1 and s.is_check = 1 and (s.type = 1 or s.type = 2)";
        if($cityid){
            $where .= " and s.circles like '%,".$cityid.",%'";
        }
        if($areaid){
            $where .= " and s.circles like '%,".$areaid."'";
        }
        if($pid){
            $where .= " and g.p_cat = ".$pid;
        }
        if($sub_id){
            $where .= " and g.sub_cat = ".$sub_id;
        }
        if($ord == 1){
            $order = "g.salenum desc";
        }elseif($ord == 2){
            $order = "g.discount desc";
        }elseif($ord == 3){
            $order = "g.discount asc";
        }
        if (!$pagesize) {
            $pagesize = 20;
        }
        if (!$startrow) {
            $startrow = 0;
        }
        $count = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->where($where)->count();
        $nums = ceil($count/$pagesize);
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesize;
        $results = array();
        $results['status'] == 0;
        $results['data']['total'] = $count;
        $results['data']['startrow'] = $startrow;
        $results['data']['nums'] = $nums;
        if ($count > 0) {
            $field = "g.id,g.name,g.img,c.name as cate,ca.name as sub_cate,g.discount,g.price,g.salenum,g.valid_time,g.no_valid_time_start,g.no_valid_time_end,g.recommend,s.circles,s.addr,s.min_discount";
            if($x && $y){
                $where .= " and s.map_y is not null and s.map_x is not null";
                $field .= ',round(6378.138*2*asin(sqrt(pow(sin(('.$x.'*pi()/180-s.map_x*pi()/180)/2),2)+cos('.$x.'*pi()/180)*cos(s.map_x*pi()/180)* pow(sin(('.$y.'*pi()/180-s.map_y*pi()/180)/2),2))),2) as dis';
                if(!$order){
                    $order = 'dis asc,g.ord desc';
                }else{
                    $order .= ',dis asc,g.ord desc';
                }
            }else{
                if(!$order){
                    $order = 'g.ord desc';
                }else{
                    $order .= ',g.ord desc';
                }
            }
            $lists = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->field($field)->where($where)->limit($limit.",".$pagesize)->order($order)->select();
            $results['data']['rows'] = $lists;
        }else{
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    /*
     * @chenxuan
     * 团购列表
     * 2015-5-6
     */

    public function away_goods() {
        $attr = $_REQUEST['attr'];
        $cityid = $_REQUEST['cityid'];
        $circleid = $_REQUEST['circleid'];
        $cateid = $_REQUEST['cateid'];
        $sub_cateid = $_REQUEST['sub_cateid'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $recommend = $_REQUEST['recommend'];
        $ord = $_REQUEST['ord'];
        $where = "g.is_check=1 and s.type > 1";
        if ($recommend) {
            $where .= " and g.recommend = $recommend ";
        }
        if($cityid){
            $where .= " and s.circles like '%,".$cityid.",%'";
        }
        if($circleid){
            $where .= " and s.circles like '%,".$circleid."'";
        }
        if($cateid){
            $where .= " and g.p_cat = ".$cateid;
        }
        if($sub_cateid){
            $where .= " and g.sub_cat = ".$sub_cateid;
        }
        if($ord == 1){
            $order = "g.salenum,";
        }
        if($ord == 2){
            $order = "g.discount desc,";
        }
        if($ord == 3){
            $order = "g.discount asc,";
        }
        if (empty($pagesizes)) {
            $pagesizes = 20;
        }
        if (empty($startrow)) {
            $startrow = 0;
        }
        $count = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->where($where)->count();
        $nums = ceil($count/$pagesizes);
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesizes;
        $results = array();
        $results['status'] == '00';
        $results['data']['total'] = $count;
        $results['data']['startrow'] = $startrow;
        $results['data']['nums'] = $nums;
        if ($count > 0) {
            $lists = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->field("g.id,g.name,g.img,c.name as cate,ca.name as sub_cate,g.discount,g.price,g.salenum,g.valid_time,g.no_valid_time_start,g.no_valid_time_end,g.recommend,s.circles,s.addr")->where($where)->limit($limit.",".$pagesizes)->order($order." g.ord,g.id desc")->select();
            foreach ($lists as & $val) {
                $len_name = mb_strlen($val['name'],'utf-8');
                if($len_name > 8){
                    $val['name'] = mb_substr($val['name'],0,8,'utf-8');
                }
                $len_intro = mb_strlen($good['intro'],'utf-8');
                if($val['img']){
                    $img_array = explode(",",$val['img']);
                    if($img_array){
                        $val['img'] = C('SITE_URL') . C('goodsFile') . $img_array[0];
                    }
                }
            }
            $results['data']['rows'] = $lists;
        }else{
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    public function get_map_goods(){
        $attr = $_REQUEST['attr'];
        $cityid = $_REQUEST['cityid'];
        $circleid = $_REQUEST['circleid'];
        $cateid = $_REQUEST['cateid'];
        $sub_cateid = $_REQUEST['sub_cateid'];
        $where = "g.is_check=1";
        if ($recommend) {
            $where .= " and g.recommend = $recommend ";
        }
        if($cityid){
            $where .= " and s.circles like '%,".$cityid.",%'";
        }
        if($circleid){
            $where .= " and s.circles like '%,".$circleid."'";
        }
        if($cateid){
            $where .= " and g.p_cat = ".$cateid;
        }
        if($sub_cateid){
            $where .= " and g.sub_cat = ".$sub_cateid;
        }
        if($ord == 1){
            $order = "g.salenum,";
        }
        if($ord == 2){
            $order = "g.discount desc,";
        }
        if($ord == 3){
            $order = "g.discount asc,";
        }
        if (empty($pagesizes)) {
            $pagesizes = 10;
        }
        if (empty($startrow)) {
            $startrow = 0;
        }
        $lists = M('goods g')->join("left join meal_shop s on (g.sid = s.id) left join meal_category c on (g.p_cat = c.id) left join meal_category ca on (g.sub_cat = ca.id)")->field("s.map_x,s.map_y,s.name")->where($where)->select();
        echo json_encode($lists);
        exit;
    }

    public function cart_get_good(){
        $id = $_REQUEST['id'];
        $good = M('goods')->field('id,name,discount')->where('id='.$id)->find();
        echo json_encode($good);
        exit;
    }

    public function delete_cart_dish(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $result = array();
        if(!$id || !$user_id){
            $result['status'] = 1;
            $result['msg'] = "参数错误";
        }else{
            $count = M("dish_cart")->where("id = ".$id." and user_id = ".$user_id)->count();
            if(!$count){
                $result['status'] = 1;
                $result['msg'] = "参数异常";
            }else{
                $res = M("dish_cart")->where("id = ".$id)->save(array("amount"=>0));
                if($res){
                    $count_re = M("dish_cart")->where("user_id = ".$user_id." and status = 0 and amount > 0")->count();
                    $result['status'] = 0;
                    $result['msg'] = "请求成功";
                    $result['count'] = $count_re;
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "删除失败";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function get_away_cart(){
        $user_id = $_REQUEST['user_id'];
        $city_id = $_REQUEST['city_id'];
        $result = array();
        if(!$user_id || !$city_id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $list = M("dish_cart c")->join("left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id) left join meal_shop s on (d.shop_id = s.id) left join meal_active_dishes a on (g.active_id = a.id)")->field("c.id,c.dish_id,c.gg_id,c.amount,d.name,d.img,c.unit_price as price,g.gg,d.shop_id,d.is_out,g.price_tuan,d.active_gg,d.active_max_num")->where("c.status = 0 and c.amount > 0 and c.user_id = ".$user_id." and s.circles like '%,".$city_id.",%' and ((c.gg_id > 0) or (c.gg_id = 0 and d.is_active = 1)) and (g.status != 0 or (c.gg_id = 0 and d.is_active = 1)) and (g.active_id = 0 or (a.begintime < ".time()." and a.deadline > ".time()."))")->select();
            $res = M("dish_cart c")->join("left join meal_dish_gg g on (c.gg_id = g.id) left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_shop s on (d.shop_id = s.id) left join meal_active_dishes a on (g.active_id = a.id)")->where("c.status = 0 and c.amount > 0 and c.user_id = ".$user_id." and d.is_out = 0 and s.circles like '%,".$city_id.",%' and ((c.gg_id > 0) or (c.gg_id = 0 and d.is_active = 1)) and (g.status != 0 or (c.gg_id = 0 and d.is_active = 1)) and (g.active_id = 0 or (a.begintime < ".time()." and a.deadline > ".time()."))")->getField("sum(c.unit_price * c.amount) as sum");
            if(!$res){
                $res = 0;
            }
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['list'] = $list;
            $result['total_price'] = $res;
        }
        echo json_encode($result);
        exit;
    }

    public function getCitySendLine(){
        $city_id = $_REQUEST['city_id'];
        $result = array();
        if(!$city_id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $send_line = M("area")->where("id = ".$city_id)->getField("send_line");
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['send_line'] = $send_line;
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 团购商品详情
     * @chenxuan
     * 2015-5-6
     */

    public function goods_detail() {
        $id = $_REQUEST['id'];
        if ($id == 0 || empty($id)) {
            $results = array(
                'status' => '01',
                'status_msg' => '参数异常'
            );
        } else {
            $detail = M("goods")->where("id =".$id)->find();
            $nowtime = time();
            if($detail['valid_time'] == '0000-00-00 00:00:00'){
                $detail['valid_time'] = '2020-12-31 23:59:59';
            }
            $remaining_time = (strtotime($detail['valid_time'])-$nowtime)/(3600*24);
            if($remaining_time >= 3){
                $detail['remaining_time'] = "剩余3天以上";
            }
            if($remaining_time >= 10){
                $detail['remaining_time'] = "剩余10天以上";
            }
            if($remaining_time <= 0){
                $detail['remaining_time'] = "已结束";
            }
            if($detail['img']){
                $arr = explode(',',$detail['img']);
                if($arr){
                    foreach ($arr as &$img) {
                        $img = C('SITE_URL').C('goodsFile').$img;
                    }
                }
                $detail['img'] = $arr;
            }
            $shop_detail = M("shop")->where("id = ".$detail['sid'])->find();
            $goods = M("goods g")->field("g.id,g.name,g.sid,g.sub_cat,g.salenum,g.img,g.discount,g.price,c.name as cat,s.min_discount,s.circles")->join("left join meal_category c on (g.sub_cat = c.id) left join meal_shop s on (g.sid = s.id)")->order("g.ord ASC")->where("g.id != ".$id." and g.sid = ".$detail['sid']." and g.is_check=1")->select();
            $results = array(
                'status' => '00',
                'data' => array(
                    'detail' => $detail,
                    'shop_detail' => $shop_detail,
                    'goods' => $goods,
                )
            );
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 商品分类
     * @chenxuan
     * 2015-5-7
     */

    public function goods_cats() {
        $sid = $_REQUEST['sid'];
        $sql = "is_check=1";
        if ($sid) {
            $sql .= " and sid = $sid";
        }
        $count = M('goods_cat')->where($sql)->count();
        $results = array();
        $results['status'] == '00';
        $results['data']['total'] = $count;
        if ($count > 0) {
            $lists = M('goods_cat')->where($sql)->order('ord ASC,id DESC')->select();
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    /*
     * @chenxuan
     * 获取两点之间的距离
     * 2015-06-01
     */

    function distanceBetween($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon) {
        $fEARTH_RADIUS = 6378137;
        //角度换算成弧度
        $fRadLon1 = deg2rad($fP1Lon);
        $fRadLon2 = deg2rad($fP2Lon);
        $fRadLat1 = deg2rad($fP1Lat);
        $fRadLat2 = deg2rad($fP2Lat);
        //计算经纬度的差值
        $fD1 = abs($fRadLat1 - $fRadLat2);
        $fD2 = abs($fRadLon1 - $fRadLon2);
        //距离计算
        $fP = pow(sin($fD1 / 2), 2) +
                cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2 / 2), 2);
        return intval($fEARTH_RADIUS * 2 * asin(sqrt($fP)) + 0.5)/1000;
    }

    /**
     * 商家入驻
     * @queyuan
     * 2015-08-12
     */
    public function add_shop(){
        $data = array();
        $data['createtime'] = time();
        $data['is_start_phone'] = 1;
        $data['is_start_email'] = 1;
        $data['pkg'] = "B";
        $data['username'] = $_REQUEST['phone'];
        $data['qq'] = $_REQUEST['qq'];
        $data['sfz'] = $_REQUEST['sfz'];
        $data['enter_rate'] = 5;
        $password = $_REQUEST['password'];
        if($password){
            $password = md5($password);
        }
        $data['password'] = $password;
        $data['name'] = $_REQUEST['name'];
        $data['type'] = 1;
        $data['goods_type'] = $_REQUEST['goods_type'];
        $data['goods_sub_types'] = $_REQUEST['goods_sub_types'];
        $data['addr'] = $_REQUEST['addr'];
        $data['star'] = 1;
        $data['ord'] = 0;
        $data['is_check'] = 0;
        $data['phone'] = $_REQUEST['phone'];
        $data['email'] = $_REQUEST['email'];
        $data['telphone'] = $_REQUEST['telphone'];
        $data['bank'] = $_REQUEST['bank'];
        $data['bank_account'] = $_REQUEST['bank_account'];
        $data['account_name'] = $_REQUEST['account_name'];
        $data['map_x'] = $_REQUEST['map_x'];
        $data['map_y'] = $_REQUEST['map_y'];
        $data['circles'] = $_REQUEST['circles'];
        $data['logo'] = $_REQUEST['logo'];
        $data['contract_img'] = $_REQUEST['contract_img'];
        $res = M("shop_apply")->add($data);
        if($res){
            $result['status'] = 0;
            $result['msg'] = "操作成功";
        }else{
            $result['status'] = 1;
            $result['msg'] = "操作失败";
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 商家列表
     * @chenxuan
     * 2015-5-7
     */

    public function shops() {
        $seid = session_id();
        $pid = $_REQUEST['pid'];
        $startrow = $_REQUEST['startrow'];
        $order = $_REQUEST['order'];
        $category = $_REQUEST['category'];
        $circles = $_REQUEST['circles'];
        $cityid = $_REQUEST['cityid'];
        $x = $_REQUEST['x'];
        $y = $_REQUEST['y'];
        $keyword = $_REQUEST['keyword'];
        $sql = "(type = 1 or type = 3) and is_check = 1 and map_x > 0 and map_y > 0";
        if ($keyword) {
            $shoparr = M('goods')->where("name like '%" . $keyword . "%'")->getField('id,sid');
            $shopstring = implode(',', $shoparr);
            $sql .= " and (name like '%" . $keyword . "%' or id in($shopstring)) ";
        }
        if($x && $y){
            $x = round($x,6);
            $y = round($y,6);
        }
        if ($pid) {
            $sql .= " and goods_type=$pid ";
        }
        if($cityid){
            $sql .= " and circles like '%,$cityid,%' ";
        }
        if ($circles) {
            $sql .= " and circles like '%,$circles' ";
        }
        if ($category) {
            $sql .= " and (goods_sub_types like '$category,%' or goods_sub_types like '$category' or goods_sub_types like '%,$category,%' or goods_sub_types like '%,$category') ";
        }
        if (empty($pagesizes)) {
            $pagesizes = 20;
        }
        if (!empty($order)) {
            $orders = $order.',id DESC';
        }
        $count = M('shop')->where($sql)->count();
        $results = array();
        $results['status'] == '00';
        $results['data']['total'] = $count;
        $nums = ceil($count/$pagesizes);
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        if (empty($startrow)) {
            $limit = 0;
        } else {
            $limit = $startrow * $pagesizes;
        }
        $results['data']['startrow'] = $startrow;
        $results['data']['nums'] = $nums;
        if ($count > 0) {
            $field = 'id,pid,username,name,logo,telphone,type,goods_type,goods_sub_types,star,addr,circles,map_x,map_y,ord,is_check,min_discount';
            if($x && $y){
                $field .= ',round(6378.138*2*asin(sqrt(pow(sin(('.$x.'*pi()/180-map_x*pi()/180)/2),2)+cos('.$x.'*pi()/180)*cos(map_x*pi()/180)* pow(sin(('.$y.'*pi()/180-map_y*pi()/180)/2),2))),2) as dis';
                if(!$order){
                    $order = 'dis asc';
                }
            }
            $lists = M('shop')->field($field)->where($sql)->order($order)->limit($limit,$pagesizes)->select();
            foreach ($lists as &$item) {
                $cir_arr = explode(",",$item['circles']);
                $item['area'] = M('area')->where('id='.$cir_arr[2])->getField('name');
                $item['salenum'] = M('goods')->where("sid=".$item['id']." and is_check = 1")->getField('sum(salenum)');
                if(!$item['salenum']){
                    $item['salenum'] = 0;
                }
                $item['goods'] = M('goods')->field('id,name,discount,price,salenum,img,intro')->where("sid=".$item['id']." and is_check=1")->limit(0,2)->select();
                foreach ($item['goods'] as &$good) {
                    $img_arr = explode(",",$good['img']);
                    $good['img'] = C('SITE_URL').C('goodsFile').$img_arr[0];
                    $len_intro = mb_strlen($good['intro'],'utf-8');
                    if($len_intro > 40){
                        $good['intro'] = mb_substr($good['intro'],0,40,'utf-8')."...";
                    }
                }
                $type_arr = explode(",",$item['goods_sub_types']);
                foreach ($type_arr as &$type) {
                    $types_arr = array();
                    $types_arr[] = M('category')->where('id='.$type)->getField('name');
                    $types = implode("/",$types_arr);
                }
                $item['types'] = $types;
            }
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    public function shops2() {
        $seid = session_id();
        $pid = $_REQUEST['pid'];
        $sub_id = $_REQUEST['sub_id'];
        $cityid = $_REQUEST['cityid'];
        $areaid = $_REQUEST['areaid'];
        $pagesize = $_REQUEST['pagesize'];
        $startrow = $_REQUEST['startrow'];
        $x = round($_REQUEST['x'],6);
        $y = round($_REQUEST['y'],6);
        $keyword = $_REQUEST['keyword'];
        $sql = "(type = 1 or type = 3) and is_check = 1";
        if($x && $y){
            $sql .= " and map_x > 0 and map_y > 0";
        }
        if ($pid) {
            $sql .= " and goods_type = ".$pid;
        }
        if($cityid){
            $sql .= " and circles like '%,".$cityid.",%'";
        }
        if ($areaid) {
            $sql .= " and circles like '%,".$areaid."'";
        }
        if ($sub_id) {
            $sql .= " and (goods_sub_types like '".$sub_id.",%' or goods_sub_types like '".$sub_id."' or goods_sub_types like '%,".$sub_id.",%' or goods_sub_types like '%,".$sub_id."') ";
        }
        if (!$pagesize) {
            $pagesize = 20;
        }
        $count = M('shop')->where($sql)->count();
        $results = array();
        $results['status'] = 0;
        $results['data']['total'] = $count;
        $nums = ceil($count/$pagesize);
        if (!$startrow) {
            $startrow = 0;
        }
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesize;
        $results['data']['startrow'] = $startrow;
        $results['data']['nums'] = $nums;
        if ($count > 0) {
            $field = 'id,pid,username,name,logo,telphone,type,goods_type,goods_sub_types,star,addr,circles,map_x,map_y,ord,is_check,min_discount';
            if($x && $y){
                $field .= ',round(6378.138*2*asin(sqrt(pow(sin(('.$x.'*pi()/180-map_x*pi()/180)/2),2)+cos('.$x.'*pi()/180)*cos(map_x*pi()/180)* pow(sin(('.$y.'*pi()/180-map_y*pi()/180)/2),2))),2) as dis';
                $order = 'dis asc,ord desc';
            }else{
                $order = "ord desc";
            }
            $lists = M('shop')->field($field)->where($sql)->order($order)->limit($limit,$pagesize)->select();
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 外卖商家列表
     * @chenxuan
     * 2015-5-7
     */

    public function away_shops() {
        $seid = session_id();
        $pid = $_REQUEST['pid'];
        $startrow = $_REQUEST['startrow'];
        $order = $_REQUEST['order'];
        $category = $_REQUEST['category'];
        $circles = $_REQUEST['circles'];
        $cityid = $_REQUEST['cityid'];
        $x = $_REQUEST['x'];
        $y = $_REQUEST['y'];
        $keyword = $_REQUEST['keyword'];
        $sql = "(type = 2 or type = 3) and is_check = 1 and map_x > 0 and map_y > 0";
        if ($keyword) {
            $shoparr = M('goods')->where("name like '%" . $keyword . "%'")->getField('id,sid');
            $shopstring = implode(',', $shoparr);
            $sql .= " and (name like '%" . $keyword . "%' or id in($shopstring)) ";
        }
        if($x && $y){
            $x = round($x,6);
            $y = round($y,6);
        }
        if ($pid) {
            $sql .= " and goods_type=$pid ";
        }
        if($cityid){
            $sql .= " and circles like '%,$cityid,%' ";
        }
        if ($circles) {
            $sql .= " and circles like '%,$circles' ";
        }
        if ($category) {
            $sql .= " and (goods_sub_types like '$category,%' or goods_sub_types like '$category' or goods_sub_types like '%,$category,%' or goods_sub_types like '%,$category') ";
        }
        if (empty($pagesizes)) {
            $pagesizes = 20;
        }
        if (!empty($order)) {
            $orders = $order.',id DESC';
        }
        $count = M('shop')->where($sql)->count();
        $results = array();
        $results['status'] == '00';
        $results['data']['total'] = $count;
        $nums = ceil($count/$pagesizes);
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        if (empty($startrow)) {
            $limit = 0;
        } else {
            $limit = $startrow * $pagesizes;
        }
        $results['data']['startrow'] = $startrow;
        $results['data']['nums'] = $nums;
        if ($count > 0) {
            $field = 'id,pid,username,name,logo,telphone,type,goods_type,goods_sub_types,star,addr,circles,map_x,map_y,ord,is_check,min_discount,addr';
            if($x && $y){
                $field .= ',ROUND(10 * 6378.137* ASIN(SQRT(POW(SIN(PI()*('.$y.'-map_y)/360),2)+COS(PI()*'.$x.'/180)* COS('.$x.' * PI()/180)*POW(SIN(PI()*('.$x.'-map_x)/360),2))),2) as dis';
                if(!$order){
                    $order = 'dis asc';
                }
            }
            $lists = M('shop')->field($field)->where($sql)->order($order)->limit($limit,$pagesizes)->select();
            foreach ($lists as &$item) {
                $item['salenum'] = M('goods')->where("sid=".$item['id']." and is_check = 1")->getField('sum(salenum)');
                if(!$item['salenum']){
                    $item['salenum'] = 0;
                }
            }
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    public function arr_sort($sort,$array){
        $arrSort = array();
        foreach($array AS $uniqid => $row){  
            foreach($row AS $key=>$value){  
                $arrSort[$key][$uniqid] = $value;  
            }  
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']),$array);
        }
        return $array;
    }

    /*
     * 商家详情
     * @chenxuan
     * 2015-5-7
     */

    public function shops_detail() {
        $id = $_REQUEST['id'];
        $type = $_REQUEST['type'];
        $sql = "is_check=1";
        if ($id) {
            $sql .= " and id=$id ";
        }
        if ($type) {
            $sql .= " and type=$type ";
        }
        $count = M('shop')->where($sql)->count();
        if ($count == 1) {
            $detail = M('shop')->where($sql)->find();
            if ($detail['type'] != 2) {
                $detail['tuan_goods'] = M('goods')->where("is_check=1 and sid=$detail[id]")->select();
                $results = array(
                    'status' => '00',
                    'data' => array(
                        'rows' => $detail,
                    )
                );
            } elseif ($detail['type'] == 2) {
                $detail['away_goods'] = M('away')->where("is_check=1 and sid=$detail[id]")->select();
                $results = array(
                    'status' => '00',
                    'data' => array(
                        'rows' => $detail,
                    )
                );
            } else {
                $detail['tuan_goods'] = M('goods')->where("is_check=1 and sid=$detail[id]")->select();
                $detail['away_goods'] = M('away')->where("is_check=1 and sid=$detail[id]")->select();
                $results = array(
                    'status' => '00',
                    'data' => array(
                        'rows' => $detail,
                    )
                );
            }
        } else {
            $results = array(
                'status' => '01',
                'status_msg' => '该商家不存在'
            );
        }
        echo json_encode($results);
        exit;
    }

    public function getShopId(){
        $city_id = $_REQUEST['city_id'];
        $id_fruit = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '49,%' or goods_sub_types like '%,49,%' or goods_sub_types like '%,49') and is_check = 1 and type = 2")->getField("id");
        $id_veg = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '52,%' or goods_sub_types like '%,52,%' or goods_sub_types like '%,52') and is_check = 1 and type = 2")->getField("id");
        $result = array("id_fruit"=>$id_fruit,"id_veg"=>$id_veg);
        $result['city_name'] = M("area")->where("id = ".$city_id)->getField("name");
        echo json_encode($result);
        exit;
    }

    public function getShopId2($city_id){
        $id_fruit = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '49,%' or goods_sub_types like '%,49,%' or goods_sub_types like '%,49') and is_check = 1 and type = 2")->getField("id");
        $id_veg = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '52,%' or goods_sub_types like '%,52,%' or goods_sub_types like '%,52') and is_check = 1 and type = 2")->getField("id");
        $result = array("id_fruit"=>$id_fruit,"id_veg"=>$id_veg);
        return json_encode($result);
    }

    public function getShopId3(){
        $city_id = $_REQUEST['city_id'];
        $user_x = $_REQUEST['user_y'];
        $user_y = $_REQUEST['user_x'];
        $count_fruit = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '49,%' or goods_sub_types like '%,49,%' or goods_sub_types like '%,49') and is_check = 1 and type = 2")->count();
        $count_veg = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '52,%' or goods_sub_types like '%,52,%' or goods_sub_types like '%,52') and is_check = 1 and type = 2")->count();
        if($count_fruit < 2 && $count_fruit > 0){
            $shop_fruit = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '49,%' or goods_sub_types like '%,49,%' or goods_sub_types like '%,49') and is_check = 1 and type = 2")->field("id,name")->find();
            $id_fruit = $shop_fruit['id'];
            $name_fruit = $shop_fruit['name'];
        }elseif($count_fruit >= 2){
            $shop_fruit = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '49,%' or goods_sub_types like '%,49,%' or goods_sub_types like '%,49') and is_check = 1 and type = 2")->field("id,name,round(6378.138*2*asin(sqrt(pow(sin((".$user_x."*pi()/180-map_x*pi()/180)/2),2)+cos(".$user_x."*pi()/180)*cos(map_x*pi()/180)* pow(sin((".$user_y."*pi()/180-map_y*pi()/180)/2),2))),2) as dis")->order("dis asc")->find();
            $id_fruit = $shop_fruit['id'];
            $dis_fruit = $shop_fruit['dis'];
            $name_fruit = $shop_fruit['name'];
        }
        if($count_veg < 2 && $count_veg > 0){
            $shop_veg = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '52,%' or goods_sub_types like '%,52,%' or goods_sub_types like '%,52') and is_check = 1 and type = 2")->field("id,name")->find();
            $id_veg = $shop_veg['id'];
            $name_veg = $shop_veg['name'];
        }elseif($count_veg >= 2){
            $shop_veg = M("shop")->where("circles like '%,".$city_id.",%' and (goods_sub_types like '52,%' or goods_sub_types like '%,52,%' or goods_sub_types like '%,52') and is_check = 1 and type = 2")->field("id,name,round(6378.138*2*asin(sqrt(pow(sin((".$user_x."*pi()/180-map_x*pi()/180)/2),2)+cos(".$user_x."*pi()/180)*cos(map_x*pi()/180)* pow(sin((".$user_y."*pi()/180-map_y*pi()/180)/2),2))),2) as dis")->order("dis asc")->find();
            $id_veg = $shop_veg['id'];
            $dis_veg = $shop_veg['dis'];
            $name_veg = $shop_veg['name'];
        }
        $result = array("id_fruit"=>$id_fruit,"id_veg"=>$id_veg,"name_fruit"=>$name_fruit,'name_veg'=>$name_veg);
        $result['city_name'] = M("area")->where("id = ".$city_id)->getField("name");
        echo json_encode($result);
        exit;
    }

    /*
     * 商家分类
     * @chenxuan
     * 2015-5-7
     */

    public function shops_cats() {
        $pid = $_REQUEST['pid'];
        if ($pid) {
            $sql .= " and pid = $pid";
        }
        $count = M('dictionary')->where($sql)->count();
        $results = array();
        $results['status'] == '00';
        $results['data']['total'] = $count;
        if ($count > 0) {
            $lists = M('dictionary')->where($sql)->order('ord ASC,id DESC')->select();
            $results['data']['rows'] = $this->generateTree($lists);
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    public function coupons(){
        $startrow = $_REQUEST['startrow'];
        $count = M("coupon")->where("status = 1 and flag = 0")->count();
        $pagesize = 20;
        $nums = ceil($count/$pagesize);
        if(empty($startrow)){
            $startrow = 0;
        }
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums - 1;
        }
        $limit = $startrow * $pagesize;
        $list = M("coupon")->where("status = 1 and flag = 0")->order("ord desc")->limit($limit,$pagesize)->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'coupons'=>$list,
            'nums'=>$nums,
            'startrow'=>$startrow,
        );
        echo json_encode($result);
        exit;
    }

    public function coupon_detail(){
        $id = $_REQUEST['id'];
        $coupon = M("coupon_user u")->join("left join meal_coupon c on (u.coupon_id = c.id)")->where("u.id = ".$id." and u.status = 0")->field("c.price")->find();
        if($coupon){
            $result = array(
                'status'=>0,
                'msg'=>'请求成功',
                'coupon'=>$coupon,
            );
        }else{
            $result = array(
                'status'=>1,
                'msg'=>'无此红包',
            );
        }
        echo json_encode($result);
        exit;
    }

    public function user_coupons(){
        $user_id = $_REQUEST['user_id'];
        $startrow = $_REQUEST['startrow'];
        $status = $_REQUEST['status'];
        $type = $_REQUEST['type'];
        if(empty($status)){
            $sql = "u.user_id = ".$user_id;
        }else{
            $sql = "u.user_id = ".$user_id." and status = ".$status;
        }
        if(empty($type)){
            $sql = "u.user_id = ".$user_id;
        }else{
            $sql = "u.user_id = ".$user_id." and u.status = ".$status." and c.type in (".$type.")";
        }
        $count = M("coupon_user")->where("user_id = ".$user_id)->count();
        $pagesize = 20;
        $nums = ceil($count/$pagesize);
        if(empty($startrow)){
            $startrow = 0;
        }
        if($startrow <= 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums - 1;
        }
        $limit = $startrow * $pagesize;
        $sql .= " and c.label_id = 0";
        $list = M("coupon_user u")->join("left join meal_coupon c on (u.coupon_id = c.id)")->where($sql)->field("u.id,c.name,u.coupon_id,c.price,c.value,u.status,c.type,c.flag,u.add_time,c.memo,c.use_deadline")->order('u.status asc,u.add_time asc')->limit($limit.",".$pagesize)->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'coupons'=>$list,
            'nums'=>$nums,
            'startrow'=>$startrow
        );
        echo json_encode($result);
        exit;
    }

    public function user_coupons3(){
        $user_id = $_REQUEST['user_id'];
        $startrow = $_REQUEST['startrow'];
        $status = $_REQUEST['status'];
        $type = $_REQUEST['type'];
        if(empty($status)){
            $sql = "u.user_id = ".$user_id." and (u.deadline > ".time()." or u.deadline = 0)";
        }else{
            $sql = "u.user_id = ".$user_id." and u.status = ".$status." and (u.deadline > ".time()." or u.deadline = 0)";
        }
        if(empty($type)){
            $sql = "u.user_id = ".$user_id." and (u.deadline > ".time()." or u.deadline = 0)";
        }else{
            $sql = "u.user_id = ".$user_id." and u.status = ".$status." and c.type in (".$type.") and (u.deadline > ".time()." or u.deadline = 0)";
        }
        $count = M("coupon_user")->where("user_id = ".$user_id." and (deadline > ".time()." or deadline = 0)")->count();
        $pagesize = 20;
        $nums = ceil($count/$pagesize);
        if(empty($startrow)){
            $startrow = 0;
        }
        if($startrow <= 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums - 1;
        }
        $limit = $startrow * $pagesize;
        $list = M("coupon_user u")->join("left join meal_coupon c on (u.coupon_id = c.id)")->where($sql)->field("u.id,c.name,u.coupon_id,c.price,c.value,u.status,c.type,c.flag,u.add_time,c.memo,c.use_deadline,u.deadline")->order('u.status asc,u.add_time asc')->limit($limit.",".$pagesize)->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'coupons'=>$list,
            'nums'=>$nums,
            'startrow'=>$startrow
        );
        echo json_encode($result);
        exit;
    }

    public function user_coupons2(){
        $user_id = $_REQUEST['user_id'];
        $startrow = $_REQUEST['startrow'];
        $status = $_REQUEST['status'];
        $type = $_REQUEST['type'];
        $order_id = $_REQUEST['order_id'];
        if(empty($status)){
            $sql = "u.user_id = ".$user_id;
        }else{
            $sql = "u.user_id = ".$user_id." and u.status = ".$status;
        }
        if(empty($type)){
            $sql = "u.user_id = ".$user_id;
        }else{
            $sql = "u.user_id = ".$user_id." and u.status = ".$status." and c.type in (".$type.") and (u.deadline >= ".time()." or u.deadline = 0)";
        }
        $count = M("coupon_user")->where("user_id = ".$user_id." and status = ".$status." and (deadline >= ".time()." or deadline = 0)")->count();
        $pagesize = 20;
        $nums = ceil($count/$pagesize);
        if(empty($startrow)){
            $startrow = 0;
        }
        if($startrow <= 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums - 1;
        }
        $limit = $startrow * $pagesize;
        $list2 = array();
        $list = M("coupon_user u")->join("left join meal_coupon c on (u.coupon_id = c.id)")->where($sql)->field("u.id,c.name,u.coupon_id,c.price,c.value,u.status,c.type,c.flag,u.add_time,c.memo,c.use_deadline,c.label_id,c.min,u.deadline")->order('u.deadline asc,u.status asc,u.add_time asc')->select();
        $total_price = M("away_order")->where("id = ".$order_id)->getField("total_price");
        foreach ($list as $item) {
            if(floatval($total_price) >= floatval($item['min'])){
                $list2[] = $item;
            }
        }
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'coupons'=>$list2,
            'nums'=>$nums,
            'startrow'=>$startrow
        );
        echo json_encode($result);
        exit;
    }

    public function user_invitation(){
        $user_id = $_REQUEST['user_id'];
        $result = array();
        $invitation = M("user")->where("id = ".$user_id." and is_check > 0")->getField("invitation");
        if($invitation){
            $result['status'] = 0;
            $result['msg'] = '请求成功';
            $result['invitation'] = $invitation;
        }else{
            do {
                $invitation = $this->get_invitation();
                break;
            } while (check_invitation($invitation) > 0);
            $data = array('invitation'=>$invitation);
            $res = M("user")->where("id = ".$user_id)->save($data);
            if($res){
                $result['status'] = 0;
                $result['msg'] = '请求成功';
                $result['invitation'] = $invitation;
            }else{
                $result['status'] = 1;
                $result['msg'] = '生成失败';
            }
        }
        echo json_encode($result);
        exit;
    }

    public function check_invite_num(){
        $num = $_REQUEST['num'];
        $result = array();
        $user = M("user")->where("invitation = '".$num."' and is_check > 0")->find();
        if($user){
            $result['status'] = 0;
            $result['msg'] = '请求成功';
            $result['user'] = $user;
        }else{
            $result['status'] = 1;
            $result['msg'] = '邀请码无效';
        }
        echo json_encode($result);
        exit;
    }

    public function user_receive(){
        $user_id = $_REQUEST['user_id'];
        $receives = M("user_receive")->where("uid = ".$user_id." and status = 1")->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'receives'=>$receives,
        );
        echo json_encode($result);
        exit;
    }

    public function userReceives(){
        $result = array();
        $user_id = $_REQUEST['user_id'];
        $startrow = $_REQUEST['startrow'];
        $order_id = $_REQUEST['order_id'];
        $sql = "uid = ".$user_id." and status = 1";
        if($order_id){
            $shop_id = M("away_order_goods")->where("order_id = ".$order_id)->getField("distinct shop_id");
            $circles = M("shop")->where("id = ".$shop_id)->getField("circles");
            $carr = explode(",",$circles);
            $city_id = $carr[1];
            if($city_id){
                $sql .= " and circles like '%,".$city_id.",%'";
            }
        }
        $pagesize = 10;
        if(!$startrow){
            $startrow = 0;
        }
        if($user_id){
            $count = M("user_receive")->where("uid = ".$user_id)->count();
            $num = ceil($count / $pagesize);
            if($startrow <= 0){
                $startrow = 0;
            }
            if($startrow > $nums){
                $starrow = $nums - 1;
            }
            $limit = $startrow * $pagesize;
            $receives = M("user_receive")->where($sql)->order("is_default desc")->select();
            foreach ($receives as &$receive) {
                $c_arr = array();
                $cir_arr = explode(",",$receive['circles']);
                foreach ($cir_arr as $cir) {
                    $c_arr[] = M("area")->where("id = ".$cir)->getField("name");
                }
                $receive['circles'] = implode(" ",$c_arr);
                $receive['city'] = M("area")->where("id = ".$cir_arr[1])->getField("name");
            }
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['receives'] = $receives;
        }else{
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }
        echo json_encode($result);
        exit;
    }

    public function userReceive(){
        $id = $_REQUEST['id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $receive = M("user_receive")->where("id = ".$id." and status = 1")->find();
            $cir_arr = explode(",",$receive['circles']);
            $receive['pid'] = $cir_arr[0];
            $receive['cid'] = $cir_arr[1];
            $receive['aid'] = $cir_arr[2];
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['receive'] = $receive;
        }
        echo json_encode($result);
        exit;
    }

    public function delete_receive(){
        $id = $_REQUEST['id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $receive = M("user_receive")->where("id = ".$id)->find();
            if($receive){
                $res = M("user_receive")->where("id = ".$id)->save(array("status"=>0));
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "请求成功";
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "删除失败";
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "参数错误";
            }
        }
        echo json_encode($result);
        exit;
    }

    public function save_receive(){
        $id = $_REQUEST['id'];
        $address = $_REQUEST['address'];
        $circles = $_REQUEST['circles'];
        $phone = $_REQUEST['phone'];
        $is_default = $_REQUEST['is_default'];
        $realname = $_REQUEST['realname'];
        $result = array();
        if(!$id || !$address || !$circles || !$phone || !$realname){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $receive = M("user_receive")->where("id=".$id)->find();
            if($receive){
                $data = array(
                    'address'=>$address,
                    'circles'=>$circles,
                    'phone'=>$phone,
                    'realname'=>$realname,
                    'is_default'=>$is_default,
                );
                if($is_default){
                    $user_id = M("user_receive")->where("id=".$id)->getField("uid");
                    if($user_id){
                        M("user_receive")->where("uid = ".$user_id." and is_default = 1")->save(array("is_default"=>0));
                    }
                }
                M("user_receive")->where("id = ".$id)->save($data);
                $result['status'] = 0;
                $result['msg'] = "请求成功";
            }else{
                $result['status'] = 1;
                $result['msg'] = "参数错误";
            }
        }
        echo json_encode($result);
        exit;
    }

    public function add_receive(){
        $uid = $_REQUEST['uid'];
        $realname = $_REQUEST['realname'];
        $phone = $_REQUEST['phone'];
        $circles = $_REQUEST['circles'];
        $address = $_REQUEST['address'];
        $is_default = $_REQUEST['is_default'];
        $result = array();
        if(!$uid || !$realname || !$phone || !$circles || !$address){
            $result['status'] = 1;
            $result['msg'] = "参数有误";
        }else{
            $data = array(
                'uid'=>$uid,
                'realname'=>$realname,
                'circles'=>$circles,
                'address'=>$address,
                'phone'=>$phone,
                'is_default'=>$is_default,
                'status'=>1,
            );
            if($is_default){
                M("user_receive")->where("uid = ".$uid." and is_default = 1")->save(array("is_default"=>0));
            }
            $res = M("user_receive")->add($data);
            if($res){
                $result['status'] = 0;
                $result['msg'] = "添加成功";
            }else{
                $result['status'] = 1;
                $result['msg'] = "添加失败";
            }
        }
        echo json_encode($result);
        exit;
    }

    public function get_recevie_detail(){
        $id = $_REQUEST['id'];
        $detail = M("user_receive")->where("id=".$id)->find();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'detail'=>$detail,
        );
        echo json_encode($result);
        exit;
    }

    public function add_receive_id_inorder(){
        $id = $_REQUEST['id'];
        $oid = $_REQUEST['oid'];
        if(!$id || !$oid){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $res = M("away_order")->where("id = ".$oid)->save(array("receive_id"=>$id));
            $r_id = M("away_order")->where("id=".$oid)->getField("receive_id");
            $result = array();
            if($id == $r_id){
                $result['status'] = 0;
                $result['msg'] = "选择成功";
            }else{
                $result['status'] = 1;
                $result['msg'] = "选择失败";
            }
        }
        echo json_encode($result);
        exit;
    }

    public function add_receive_id_inorder2(){
        $id = $_REQUEST['id'];
        $oid = $_REQUEST['oid'];
        if(!$id || !$oid){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $receive = M("user_receive")->where("id = ".$id)->find();
            if($receive){
                $res = M("away_order")->where("id = ".$oid)->save(array("receive_id"=>$id));
                $r_id = M("away_order")->where("id=".$oid)->getField("receive_id");
                $data = array(
                    'realname'=>$receive['realname'],
                    'phone'=>$receive['phone'],
                    'address'=>$receive['address'],
                    'circles'=>$receive['circles'],
                );
                $r_rec = M("away_order")->where("id = ".$oid)->save($data);
                $result = array();
                if($id == $r_id){
                    $result['status'] = 0;
                    $result['msg'] = "选择成功";
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "选择失败";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function update_cat_count(){
        $cats = M('category')->where("is_check = 1")->field('id,pid')->select();
        $cats_count = M('category')->where("is_check = 1")->count();
        $i = 0;
        foreach ($cats as $cat) {
            if($cat['pid']){
                $count = M('goods g')->join('meal_shop s on (g.sid = s.id)')->where('g.sub_cat='.$cat['id']." and g.is_check = 1 and s.is_check = 1")->count();
            }else{
                $count = M('goods g')->join('meal_shop s on (g.sid = s.id)')->where('g.p_cat='.$cat['id']." and g.is_check = 1 and s.is_check = 1")->count();
            }
            $data = array('tuan_goods_count'=>$count);
            $res = M('category')->where('id='.$cat['id'])->save($data);
            if($res){
                $i++;
            }
        }
        echo "总共：".$cats_count."个分类，修改成功了：".$i."个分类。";
        exit;
    }

    /*
     * 获取主分类
     * 2015-5-12
     * @chenxuan
     */
    public function category_index(){
        $sql = "is_check = 1 and pid = 0";
        $lists = M("category")->where($sql)->field("id,name,img")->order("ord desc")->select();
        foreach ($lists as &$item) {
            $item['img'] = C('SITE_URL').C('categoryFile').$item['img'];
        }
        echo json_encode($lists);
        exit;
    }

    /*
     * 获取外卖主分类
     * 2015-5-12
     * @chenxuan
     */
    public function away_category_index(){
        $sql = "is_check = 1 and pid = 0 and is_away = 1";
        $lists = M("category")->where($sql)->field("id,name,img")->order("ord desc")->select();
        foreach ($lists as &$item) {
            $item['img'] = C('SITE_URL').C('categoryFile').$item['img'];
        }
        echo json_encode($lists);
        exit;
    }

    /*
     * 团购分类
     * 2015-5-12
     * @chenxuan
     */

    public function category() {
        $pid = $_REQUEST['pid'];
        $sql = "is_check=1";
        if($pid){
            $sql .= " and pid = $pid";
        }else{
            $pid = 0;
        }
        $lists = M('category')->where($sql)->select();
        if($pid){
            foreach ($lists as & $item) {
                $item['img'] = C('SITE_URL') . C('categoryFile') . $item['img'];
            }
            $results = array(
                'status'=>'0',
                'data'=>array(
                    'rows'=>$lists,
                ),
            );
        }else{
            if($type == 1){
                foreach ($lists as & $item) {
                    $item['img'] = C('SITE_URL').C('categoryFile').$item['img'];
                }
                $results = array(
                    'status' => '0',
                    'data' => array(
                        'rows' => $lists,
                    )
                );
            }else{
                $results = array(
                    'status' => '0',
                    'data' => array(
                        'rows' => $this->generateTree($lists),
                    )
                );
            }
        }
        echo json_encode($results);
        exit;
    }

    /*
     * @chenxuan
     * 2015-06-02
     * 经纬度获取城市
     */

    public function get_cityid() {
        $x = $_REQUEST['x'];
        $y = $_REQUEST['y'];
        if (empty($x) || empty($y)) {
            $results = array(
                'status' => '01',
                'msg' => "未获取到当前位置"
            );
            echo json_encode($results);
            exit;
        }
        $mapurl = "http://api.map.baidu.com/geocoder?location=$y,$x&output=json&key=28bcdd84fae25699606ffad27f8da77b";
        $map_json = json_decode(file_get_contents($mapurl));
        $city = substr($map_json->result->addressComponent->city, 0, -3);
        if ($city) {
            $cityid = M('area')->where("name = '$city'")->getField('id,name');
            $results = array(
                'status' => '00',
                'cityid' => $cityid
            );
        }else{
            $results = array(
                'status' => '01',
                'msg' => "未获取到当前城市"
            );
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 区域
     * 2015-5-12
     * @chenxuan
     */

    public function area() {
        $id = $_REQUEST['id'];
        $sql = "is_check=1";
        if($id){
            $sql .= " and pid = ".$id;
        }
        $areas = M('area')->where($sql)->select();
        $results = array(
            'status' => '00',
            'data' => array(
                'rows' => $this->generateTree($areas),
            )
        );
        echo json_encode($results);
        exit;
    }

    public function area2() {
        $sql = "is_check=1 and is_away = 1 and level = 2";
        $areas = M('area')->where($sql)->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'res'=>$areas,
        );
        echo json_encode($result);
        exit;
    }

    public function away_areas(){
        $provinces = M("area")->where("level = 1 and is_check = 1 and is_away = 1")->select();
        foreach ($provinces as &$province) {
            $province['cities'] = M("area")->where("level = 2 and is_check = 1 and is_away = 1 and pid = ".$province['id'])->select();
        }
        $result = array('status'=>0,'msg'=>"请求成功",'areas'=>$provinces);
        echo json_encode($result);
        exit;
    }

    public function away_areas2(){
        $provinces = M("area")->where("level = 1 and is_check = 1 and is_away = 1")->select();
        foreach ($provinces as &$province) {
            $province['cities'] = M("area")->where("level = 2 and is_check = 1 and (is_away = 1 or is_rest = 1) and pid = ".$province['id'])->order("is_rest asc,id asc")->select();
        }
        $result = array('status'=>0,'msg'=>"请求成功",'areas'=>$provinces);
        echo json_encode($result);
        exit;
    }

    public function get_away_areas(){
        $pid = $_REQUEST['pid'];
        $areas = M("area")->where("pid = ".$pid." and is_check = 1 and is_away = 1")->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'areas'=>$areas
        );
        echo json_encode($result);
        exit;
    }

    public function get_area(){
        $city = $_REQUEST['city'];
        $area = M("area")->where("name = '".$city."' and is_away = 1")->find();
        $result = array();
        if($area){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['area'] = $area;
        }else{
            $result['status'] = 1;
            $result['msg'] = "城市暂未开启";
        }
        echo json_encode($result);
        exit;
    }

    public function area_name(){
        $id = $_REQUEST['id'];
        $name = M("area")->where("id = ".$id." and is_check = 1")->getField("name");
        $result['status'] = 0;
        $result['msg'] = "请求成功";
        $result['name'] = $name;
        echo json_encode($result);
        exit;
    }

    public function getAreaid(){
        $name = $_REQUEST['name'];
        $id = M("area")->where("name like '%".$name."%' and is_check = 1")->getField("id");
        if($id){
            $result = array('status'=>0,'msg'=>'请求成功','id'=>$id);
        }else{
            $result = array('status'=>1,'msg'=>'无此城市');
        }
        echo json_encode($result);
        exit;
    }

    public function cat_name(){
        $id = $_REQUEST['id'];
        $name = M("category")->where("id = ".$id." and is_check = 1")->getField("name");
        $result['status'] = 0;
        $result['msg'] = "请求成功";
        $result['name'] = $name;
        echo json_encode($result);
        exit;
    }

    function sysSortArray($ArrayData, $KeyName1, $SortOrder1 = "SORT_ASC", $SortType1 = "SORT_REGULAR") {
        if (!is_array($ArrayData)) {
            return $ArrayData;
        }
        $ArgCount = func_num_args();
        for ($I = 1; $I < $ArgCount; $I++) {
            $Arg = func_get_arg($I);
            if (!eregi("SORT", $Arg)) {
                $KeyNameList[] = $Arg;
                $SortRule[] = '$' . $Arg;
            } else {
                $SortRule[] = $Arg;
            }
        }
        foreach ($ArrayData AS $Key => $Info) {
            foreach ($KeyNameList AS $KeyName) {
                ${$KeyName}[$Key] = $Info[$KeyName];
            }
        }
        $EvalString = 'array_multisort(' . join(",", $SortRule) . ',$ArrayData);';
        eval($EvalString);
        return $ArrayData;
    }

    public function _getFirstCharter($str) {
        if (empty($str)) {
            return '';
        }
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z'))
            return strtoupper($str{0});
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284)
            return 'A';
        if ($asc >= -20283 && $asc <= -19776)
            return 'B';
        if ($asc >= -19775 && $asc <= -19219)
            return 'C';
        if ($asc >= -19218 && $asc <= -18711)
            return 'D';
        if ($asc >= -18710 && $asc <= -18527)
            return 'E';
        if ($asc >= -18526 && $asc <= -18240)
            return 'F';
        if ($asc >= -18239 && $asc <= -17923)
            return 'G';
        if ($asc >= -17922 && $asc <= -17418)
            return 'H';
        if ($asc >= -17417 && $asc <= -16475)
            return 'J';
        if ($asc >= -16474 && $asc <= -16213)
            return 'K';
        if ($asc >= -16212 && $asc <= -15641)
            return 'L';
        if ($asc >= -15640 && $asc <= -15166)
            return 'M';
        if ($asc >= -15165 && $asc <= -14923)
            return 'N';
        if ($asc >= -14922 && $asc <= -14915)
            return 'O';
        if ($asc >= -14914 && $asc <= -14631)
            return 'P';
        if ($asc >= -14630 && $asc <= -14150)
            return 'Q';
        if ($asc >= -14149 && $asc <= -14091)
            return 'R';
        if ($asc >= -14090 && $asc <= -13319)
            return 'S';
        if ($asc >= -13318 && $asc <= -12839)
            return 'T';
        if ($asc >= -12838 && $asc <= -12557)
            return 'W';
        if ($asc >= -12556 && $asc <= -11848)
            return 'X';
        if ($asc >= -11847 && $asc <= -11056)
            return 'Y';
        if ($asc >= -11055 && $asc <= -10247)
            return 'Z';
        return null;
    }

    /*
     * 热门区域
     * 2015-5-19
     * @chenxuan
     */

    public function hot_area() {
        $sql = "is_check=1 and level = 2";
        $areas = M('area')->where($sql)->order("ord desc")->limit(0, 10)->select();
        $results = array(
            'status' => '00',
            'data' => array(
                'rows' => $areas
            )
        );
        echo json_encode($results);
        exit;
    }

    /*
     * 评价
     * 2015-5-12
     * @chenxuan
     */

    public function comment_add() {
        $data['uid'] = $_REQUEST['uid'];
        $data['sid'] = $_REQUEST['sid'];
        $data['comment'] = $_REQUEST['comment'];
        $data['delicious'] = $_REQUEST['delicious'];
        $data['speed'] = $_REQUEST['speed'];
        $data['full'] = $_REQUEST['full'];
        $data['points'] = $_REQUEST['points'];
        $data['addtime'] = time();
        M("comment")->add($data);
        $results = array('status' => '00');
        echo json_encode($results);
        exit;
    }

    /*
     * 商品评论
     * @queyuan
     * 2015-06-15
     */

    public function good_comment(){
        $id = $_REQUEST['id'];
        $page = $_REQUEST['page'];
        $count = M('comment')->where('goods_id='.$id)->count();
        $nums = ceil($count/10);
        if($page < 0){
            $page = 0;
        }
        if($page >= $nums){
            $page = $nums - 1;
        }
        $limit = $page * 10;
        $comments = M('comment')->where('goods_id='.$id)->limit($limit,10)->select();
        $res['nums'] = $nums;
        $res['page'] = $page;
        $res['comment'] = $comments;
        echo json_encode($res);
        exit;
    }

    /*
     * 外卖订单
     * @queyuan
     * 2015-08-06
     */
    public function away_order(){
        $user_id = $_REQUEST['user_id'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $status = $_REQUEST['status'];
        $sql = " is_tuan = 0";
        if ($user_id) {
            $sql .= " and o.user_id = ".$user_id;
        } else {
            $results = array(
                'status' => 1,
                'msg' => "参数不合法"
            );
            echo json_encode($results);
            exit;
        }
        if(!$status){
            $status = 0;
        }
        $sql .= " and o.status = ".$status;
        if (empty($pagesizes)) {
            $pagesizes = 10;
        }
        if (empty($startrow)) {
            $startrow = 0;
        }
        $count = M('away_order o')->where($sql)->count();
        $results = array();
        $results['status'] = 0;
        $nums = ceil($count/$pagesizes);
        $results['data']['nums'] = $nums;
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesizes;
        $results['data']['startrow'] = $startrow;
        if ($count >= 0) {
            $lists = M('away_order o')->join("meal_away_order_goods g on (o.id = g.order_id)")->field("o.id,o.order_sn,o.total_price,o.status,sum(g.amount) as amount,o.order_time,o.flag")->where($sql)->limit($limit.','.$pagesizes)->order('o.pay_time desc,o.order_time desc')->group("o.id")->select();
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    /**
     * 检测订单是否属于该用户
     * @queyuan
     * 2015/11/7
     */
    public function check_isown(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $uid = M("away_order")->where("id = ".$id)->getField("user_id");
        $result = array();
        if($uid == $user_id){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['isown'] = 1;
        }else{
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['isown'] = 0;
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 参团下单
     * @queyuan
     * 2015/11/7
     */
    public function ctuan_add_order(){
        $result = array();
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST["user_id"];
        $count = M("away_order")->where("order_id = ".$id." and status > 0 and status < 4")->count();
        $order_id = M("away_order")->where("id = ".$id)->getField("order_id");
        if(!$order_id){
            $order_id = $id;
        }
        $order = M("away_order")->where("id = ".$order_id." and status > 0")->find();
        if($order['user_id'] == $user_id){
            $result['status'] = 1;
            $result['msg'] = "您已参团";
        }else{
            $count2 = M("away_order")->where("order_id = ".$order_id." and user_id = ".$user_id." and status > 0")->count();
            if($count2){
                $result['status'] = 1;
                $result['msg'] = "您已参团";
            }else{
                $order3 = M("away_order")->where("order_id = ".$order_id." and user_id = ".$user_id." and status = 0")->find();
                if($order3){
                    M("away_order")->where("id = ".$order3['id'])->save(array('order_time'=>time()));
                    $result['status'] = 0;
                    $result['msg'] = "下单成功，请支付！";
                    $result['order_id'] = $order3['id'];
                }else{
                    $order_goods = M("away_order_goods")->where("order_id = ".$order_id)->find();
                    $member = M("dish_gg")->where("dish_id = ".$order_goods['goods_id']." and is_tuan = 1")->getField("member");
                    if($count >= $member){
                        $result['status'] = 1;
                        $result['msg'] = "参团人数已达上限";
                    }else{
                        do {
                            $order_sn = $this->get_order_sn();
                            break;
                        } while (check_away_order($order_sn) > 0);
                        $order_data = array(
                            'order_sn' => $order_sn,
                            'user_id' => $user_id,
                            'total_price' => $order['total_price'],
                            'order_time' => time(),
                            'status' => 0,
                            'flag' => $flag,
                            'is_tuan'=>1,
                            'order_id'=>$order_id,
                        );
                        $oid = M("away_order")->add($order_data);
                        if($oid){
                            $goods_data = array(
                                'order_id'=>$oid,
                                'shop_id'=>$order_goods['shop_id'],
                                'goods_id'=>$order_goods['goods_id'],
                                'amount'=>$order_goods['amount'],
                                'goods_name'=>$order_goods['goods_name'],
                                'gg_id'=>$order_goods['gg_id'],
                                'unit_price'=>$order_goods['unit_price'],
                            );
                            M("away_order_goods")->add($goods_data);
                            $result['status'] = 0;
                            $result['msg'] = "下单成功，请支付！";
                            $result['order_id'] = $oid;
                        }else{
                            $result['status'] = 1;
                            $result['msg'] = "参团失败";
                        }
                    }
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function away_order_tuan(){
        $user_id = $_REQUEST['user_id'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $s = $_REQUEST['status'];
        $sql = " o.is_tuan = 1 and o.status = ".$s;
        if ($user_id) {
            $sql .= " and o.user_id = ".$user_id;
        } else {
            $results = array(
                'status' => 1,
                'msg' => "参数不合法"
            );
            echo json_encode($results);
            exit;
        }
        if (empty($pagesizes)) {
            $pagesizes = 10;
        }
        if (empty($startrow)) {
            $startrow = 0;
        }
        $count = M('away_order o')->where($sql)->count();
        $results = array();
        $results['status'] = 0;
        $nums = ceil($count/$pagesizes);
        $results['data']['nums'] = $nums;
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesizes;
        $results['data']['startrow'] = $startrow;
        if ($count >= 0) {
            $lists = M('away_order o')->join("left join meal_away_order_goods g on (o.id = g.order_id) left join meal_away_order o2 on (o2.order_id = o.id) left join meal_dish_gg d on (g.gg_id = d.id)")->field("o.id,o.order_sn,o.total_price,o.status,sum(g.amount) as amount,g.goods_id,o.order_time,d.member,o.order_id")->where($sql)->limit($limit.','.$pagesizes)->order('o.status desc,o.pay_time desc,o.order_time desc')->group("o.id")->select();
            if($s > 0){
                foreach ($lists as &$order) {
                    if($order['order_id']){
                        $count = M("away_order")->where("order_id = ".$order['order_id']." and status > 0 and status < 4")->count();
                        $order['count'] = $count + 1;
                    }else{
                        $count = M("away_order")->where("order_id = ".$order['id']." and status > 0 and status < 4")->count();
                        $order['count'] = $count + 1;
                    }
                }
            }
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 团购订单
     * @chenxuan
     * 2015-5-20
     */

    public function tuan_order() {
        $uid = $_REQUEST['uid'];
        $status = $_REQUEST['status'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $sql = " 1=1";
        if ($uid) {
            $sql .= " and o.user_id = $uid";
        } else {
            $results = array(
                'status' => '01',
                'msg' => "参数不合法"
            );
            echo json_encode($results);
            exit;
        }
        if (isset($status)) {
            $sql .= " and o.status = $status";
        }
        if (empty($pagesizes)) {
            $pagesizes = 10;
        }
        $count = M('tuan_order o')->join("meal_tuan_order_goods g on (o.id = g.order_id)")->where($sql)->count();
        $results = array();
        $results['status'] = 0;
        $nums = ceil($count/$pagesizes);
        $results['data']['nums'] = $nums;
        if($startrow < 0){
            $startrow = 0;
        }
        if($startrow >= $nums){
            $startrow = $nums-1;
        }
        $limit = $startrow * $pagesizes;
        $results['data']['startrow'] = $startrow;
        if ($count > 0) {
            $lists = M('tuan_order o')->join("left join meal_tuan_order_goods g on (o.id = g.order_id) left join meal_goods g1 on (g.goods_id = g1.id)")->field("o.id,o.total_price,g.amount,g1.name,g1.img,o.status,o.order_time,o.order_sn")->where($sql)->limit($limit.','.$pagesizes)->order('pay_time desc')->select();
            $results['data']['rows'] = $lists;
        } else {
            $results['data']['rows'] = array();
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 登录
     * 2015-5-12
     * @chenxuan
     */

    public function login() {
        $name = $_REQUEST['name'];
        $pwd = md5($_REQUEST['pwd']);
        $flag = $_REQUEST['flag'];
        $city_id = $_REQUEST['city_id'];
        $sql = "1=1";
        $data = array();
        if(!$name || !$pwd || !$flag){
            $data['status'] = 1;
            $data['msg'] = '登录失败';
        }else{
            if($flag != 'email' && $flag != 'phone' && $flag != 'username' && $flag != 'card'){
                $data['status'] = 1;
                $data['msg'] = '登录失败';
            }else{
                if($flag == 'email'){
                    $sql .= " and email = '".$name."' and name != '' and pwd = '".$pwd."' and is_check > 0";
                }else if($flag == 'phone'){
                    $sql .= " and phone = '".$name."' and name != '' and pwd = '".$pwd."' and is_check > 0";
                }else if($flag == 'username'){
                    $sql .= " and name = '".$name."' and and phone != '' and pwd = '".$pwd."' and is_check > 0";
                }else if($flag == 'card'){
                    $sql .= " and card_num = '".$name."' and pwd = '".$pwd."'";
                }
                $count = M('user')->where($sql)->count();
                if(!$count){
                    if($flag == 'card'){
                        $data['status'] = 1;
                        $data['msg'] = '无此卡，请重新登录';
                    }else{
                        $data['status'] = 1;
                        $data['msg'] = '账号/密码错误，请重新登录';
                    }
                }else{
                    $user = M('user')->where($sql)->field('id,name,phone,email,avatar,money,is_check')->find();
                    if($user['is_check'] == 2){
                        if($flag == 'card'){
                            $data['status'] = 1;
                            $data['msg'] = '此卡已激活，请用手机号登录';
                        }else{
                            $login_data = array('logintime'=>time(),'loginip'=>$_SERVER['REMOTE_ADDR'],'area_id'=>$city_id);
                            $res = M('user')->where("id=".$user['id'])->save($login_data);
                            if($res){
                                $data['status'] = 0;
                                $data['msg'] = '登录成功';
                                $data['user'] = $user;
                            }else{
                                $data['status'] = 1;
                                $data['msg'] = '系统异常，请稍后重试';
                            }
                        }
                    }else{
                        if($flag == 'card'){
                            $login_data = array('logintime'=>time(),'loginip'=>$_SERVER['REMOTE_ADDR'],'is_check'=>1);
                            $res = M('user')->where("id=".$user['id'])->save($login_data);
                            if($res){
                                $data['status'] = 0;
                                $data['msg'] = '登录成功';
                                $data['user'] = $user;
                            }else{
                                $data['status'] = 1;
                                $data['msg'] = '系统异常，请稍后重试';
                            }
                        }else{
                            $login_data = array('logintime'=>time(),'loginip'=>$_SERVER['REMOTE_ADDR']);
                            $res = M('user')->where("id=".$user['id'])->save($login_data);
                            if($res){
                                $data['status'] = 0;
                                $data['msg'] = '登录成功';
                                $data['user'] = $user;
                            }else{
                                $data['status'] = 1;
                                $data['msg'] = '系统异常，请稍后重试';
                            }
                        }
                    }
                    
                }
            }
        }
        echo json_encode($data);
        exit;
    }

    /*
     * 激活鲜果卡
     * 2015-9-15
     * @chenxuan
     */
    public function bind_card(){
        $bind_flag = $_REQUEST['bind_flag'];
        $phone = $_REQUEST['phone'];
        $card_id = $_REQUEST['card_id'];
        $result = array();
        if($bind_flag){
            $bind_pwd = md5($_REQUEST['bind_pwd']);
            $user = M("user")->where("phone = '".$phone."' and pwd = '".$bind_pwd."' and is_check > 0 and name is not null and name != ''")->find();
            if($user){
                $card_money = M("user")->where("id = ".$card_id." and is_check = 1")->getField("card_money");
                $money = floatval($user['money'])+floatval($card_money);
                $data = array("money"=>$money);
                $res = M("user")->where("id = ".$user['id'])->save($data);
                if($res){
                    M("user")->where("id = ".$card_id)->save(array("is_check"=>2,"phone"=>$phone));
                }
                $result['status'] = 0;
                $result['msg'] = "激活成功";
                $result['user'] = $user;
            }else{
                $result['status'] = 1;
                $result['msg'] = "密码错误";
            }
        }else{
            $yzm = $_REQUEST['yzm'];
            $count = M("codes")->where("account = '".$phone."' and rand = '".$yzm."'")->count();
            if($count){
                $user = M("user")->where("id = ".$card_id)->find();
                if($user){
                    $money = floatval($user['card_money']);
                    $data = array("money"=>$money,"phone"=>$phone,"name"=>$phone,"is_check"=>2);
                    $res = M("user")->where("id = ".$user['id'])->save($data);
                    $result['status'] = 0;
                    $result['msg'] = "激活成功";
                    $result['user'] = $user;
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "参数异常";
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "验证码错误";
            }
        }
        echo json_encode($result);
        exit;
    }

    public function jh_card(){
        $user_id = $_REQUEST['user_id'];
        $card = $_REQUEST['card'];
        $pwd = md5($_REQUEST['pwd']);
        $user_card = M("user")->where("card_num='".$card."' and pwd = '".$pwd."' and is_check < 2")->field("id,card_money")->find();
        $result = array();
        if($user_card){
            $user = M("user")->where("id = ".$user_id)->find();
            if($user){
                $money = floatval($user['money']);
                $money = $money + floatval($user_card['card_money']);
                $res = M("user")->where("id = ".$user_id)->save(array("money"=>$money));
                M("user")->where("id = ".$user_card['id'])->save(array('phone'=>$user['phone'],'is_check'=>2));
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "激活成功";
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "激活失败";
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "无此用户";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "此卡无效";
        }
        echo json_encode($result);
        exit;
    }

    public function check_pwd(){
        $id = $_REQUEST['id'];
        $pwd = md5($_REQUEST['pwd']);
        $count = M('user')->where('id='.$id.' and pwd = "'.$pwd.'"')->count();
        $results = array(
            'status'=>$count,
        );
        echo json_encode($results);
        exit;
    }

    /*
     * 验证用户
     * 2015-5-12
     * @chenxuan
     */

    public function check_user() {
        $name = $_REQUEST['name'];
        $count = M('user')->where("name = '" . $name . "'")->count();
        $results = array(
            'status' => $count
        );
        echo json_encode($results);
        exit;
    }

    /*
     * 验证手机
     * 2015-06-09
     * @queyuan
     */
    public function check_phone(){
        $mobile = $_REQUEST['mobile'];
        $id = 0;
        $count = M('user')->where("phone='".$mobile."'")->count();
        if($count){
            $id = M('user')->where('phone="'.$mobile.'"')->getField('id');
        }
        $result = array(
            'status'=>$count,
            'id'=>$id,
        );
        echo json_encode($result);
        exit;
    }

    /*
     * 修改用户名
     * @chenxuan
     * 2015-5-14
     */

    public function edit_user() {
        $name = $_REQUEST['name'];
        $id = $_REQUEST['id'];
        $data = array('name' => $name);
        M("user")->where("id = " . $id . "")->save($data);
        $results = array(
            'status' => '00'
        );
        echo json_encode($results);
        exit;
    }

    /*
     * 修改密码
     * @chenxuan
     * 2015-5-14
     */

    public function edit_password() {
        $id = $_REQUEST['id'];
        $password = md5($_REQUEST['password']);
        $new_password = md5($_REQUEST['new_password']);
        $count = M('user')->where("id = " . $id . " and pwd = '" . $password . "'")->count();
        if ($count == 0) {
            $results = array(
                'status' => '1',
                'msg' => '当前密码错误'
            );
            echo json_encode($results);
            exit;
        } else {
            $data = array('pwd' => $new_password);
            M("user")->where("id = " . $id . "")->save($data);
            $results = array(
                'status' => '0'
            );
            echo json_encode($results);
            exit;
        }
    }

    /*
     * 密码找回修改密码
     * @queyuan
     * 2015-6-9
     */
    public function update_pwd(){
        $id = $_REQUEST['id'];
        $pwd = md5($_REQUEST['pwd']);
        $data = array('pwd'=>$pwd);
        $count = M('user')->where('id='.$id)->count();
        if($count){
            $res = M('user')->where('id='.$id)->save($data);
            $result = array(
                'status'=>$res,
                'msg'=>'修改密码成功',
            );
        }else{
            $result = array(
                'status'=>0,
                'msg'=>'用户不存在',
            );
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 修改绑定手机
     * @queyuan
     * 2015-6-9
     */
    public function update_phone(){
        $id = $_REQUEST['id'];
        $phone = $_REQUEST['phone'];
        $data = array('phone'=>$phone);
        $count = M('user')->where('id='.$id)->count();
        $user = M("user")->where("id = ".$id)->find();
        if($count){
            if($user['phone']){
                $res = M('user')->where('id='.$id)->save($data);
                $result = array(
                    'status'=>$res,
                    'msg'=>'绑定成功',
                );
            }else{
                $user2 = M("user")->where("phone = '".$phone."' and name != '' and is_check > 0")->field("id",'money','integral')->find();
                if(!$user2){
                    $data['pwd'] = md5($_REQUEST['yzm']);
                    $res = M('user')->where('id='.$id)->save($data);
                    $result = array(
                        'status'=>$res,
                        'msg'=>'绑定成功',
                    );
                }else{
                    $data2 = array(
                        'name'=>$user['name'],
                        'phone'=>$user['phone'],
                        'money'=>(floatval($user2['money'])+floatval($user['money'])),
                        'integral'=>(intval($user2['integral'])+intval($user['integral'])),
                        'invite_id'=>$user['invite_id'],
                        'openid'=>$user['openid'],
                        'city'=>$user['city'],
                        'sex'=>$user['sex'],
                        'language'=>$user['lange'],
                    );
                    M("user")->where('id = '.$user2['id'])->save($data2);
                    M("away_order")->where("user_id = ".$id)->save(array('user_id'=>$user2['id']));
                    $result = array(
                        'status'=>$res,
                        'msg'=>'绑定成功',
                    );
                }
            }
        }else{
            $result = array(
                'status'=>0,
                'msg'=>'用户不存在',
            );
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 我的收藏列表
     * @chenxuan
     * 2015-5-14
     */

    public function collects() {
        $uid = $_REQUEST['uid'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $mtype = $_REQUEST['mtype'];
        if (empty($pagesizes)) {
            $pagesizes = 10;
        }
        if (empty($startrow)) {
            $startrow = 0;
        } else {
            $startrow = $startrow * $pagesizes;
        }
        $sql = "meal_collects.uid = $uid";
        if ($mtype) {
            $sql .= " and meal_collects.mtype  = $mtype ";
        }
        $count = M('collects')->where($sql)->count();
        if ($count > 0) {
            if ($mtype == 2) {
                $list = M('collects')->join('LEFT JOIN meal_shop ON meal_shop.id = meal_collects.pid')->field('meal_collects.*,meal_shop.name')->where($sql)->limit($startrow . ',' . $pagesizes)->order('meal_collects.addtime desc')->select();
            } else {
                $list = M('collects')->join('LEFT JOIN meal_goods ON meal_goods.id = meal_collects.pid')->field('meal_collects.*,meal_goods.name')->where($sql)->limit($startrow . ',' . $pagesizes)->order('meal_collects.addtime desc')->select();
            }
            $results = array(
                'status' => '00',
                'data' => array(
                    'total' => $count,
                    'rows' => $list
                )
            );
        } else {
            $results = array(
                'status' => '00',
                'data' => array(
                    'total' => $count,
                    'rows' => array()
                )
            );
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 添加收藏
     * @chenxuan
     * 2015-5-14
     */

    public function collects_add() {
        $uid = $_REQUEST['uid'];
        $sql = "1 ";
        if ($uid) {
            $sql .= " and uid = $uid ";
        } else {
            $results = array(
                'status' => '01',
                'msg' => "未登录状态"
            );
            echo json_encode($results);
            exit;
        }
        $pid = $_REQUEST['id'];
        if ($pid) {
            $sql .= " and pid = $pid ";
        }
        $mtype = $_REQUEST['mtype'];
        if ($mtype) {
            $sql .= " and mtype = $mtype ";
        }
        $count = M('collects')->where($sql)->count();
        if ($count > 0) {
            $results = array(
                'status' => '01',
                'msg' => "不能重复收藏"
            );
            echo json_encode($results);
            exit;
        } else {
            $data = array(
                'uid' => $uid,
                'pid' => $pid,
                'mtype' => $mtype,
                'addtime' => time()
            );
            M("collects")->add($data);
            $results = array(
                'status' => '00'
            );
            echo json_encode($results);
            exit;
        }
    }

    /*
     * 商家开通成功后发送短信推送
     * @阙渊
     * 2015-06-17
     */
    public function success_send(){
        $tel = $_REQUEST['tel'];
        $name = $_REQUEST['name'];
        $nopass_reason = $_REQUEST['r'];
        $mtype = 4;
        $time = M('codes')->where("account = $tel and mtype = $mtype")->getField('addtime');
        $s = 0;
        $tel_user = substr($tel,7,4);
        if(!$s){
            if(!$nopass_reason){
                $msg = "您的店铺【".$name."】申请已审核成功，您可以使用电脑访问快快送商家后台：back.gokks.com/Sell/，并登录，用户名为尾号为".$tel_user."的手机号码。欢迎成为快快送签约商家。";
            }else{
                $msg = "您的店铺【".$name."】申请审核失败，失败原因：".$nopass_reason."，您可以重新申请或联系快快送客服：0531-86391699";
            }
            $sms = send_msg($tel, $msg);
            $count = M('codes')->where("account = $tel")->count();
            if ($sms == '00') {
                $results = array(
                    'status' => 0,
                    'msg' => '发送成功'
                );
            } else {
                $results = array(
                    'status' => 1,
                    'msg' => '发送失败，请重新发送'
                );
            }
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 发送短信验证码
     * @chenxuan
     * 2015-05-20
     */

    public function send_code() {
        $tel = $_REQUEST['tel'];
        $mtype = $_REQUEST['mtype'];
        $s = 0;
        $ip = $_REQUEST['ip'];
        if(!$ip){
            $results = array(
                'status'=>1,
                'msg'=>'无法获取IP',
            );
        }else{
            $time_begin = strtotime(date("Y-m-d 00:00:00",time()));
            $time_end = strtotime(date("Y-m-d 23:59:59",time()));
            $count_ip = M("codes")->where("ip = '".$ip."' and addtime > ".$time_begin." and addtime < ".$time_end)->count();
            $count_tel = M("codes")->where("account = '".$tel."' and addtime > ".$time_begin." and addtime < ".$time_end)->count();
            if($count_ip >= 3){
                $results = array(
                    'status'=>1,
                    'msg'=>'已达上限',
                );
            }else{
                if($count_tel >= 3){
                    $results = array(
                        'status'=>1,
                        'msg'=>'已达上限',
                    );
                }else{
                    $seid = session_id();
                    $se_time = M("codes")->where("sessid = ".$seid)->order("addtime desc")->getField("addtime");
                    if($se_time){
                        $se_m = (time()-$se_time)/60;
                        if($se_m <= 1){
                            $s = 1;
                            $results = array(
                                'status' => 1,
                                'msg' => '请一分钟后再试',
                            );
                        }else{
                            $s = 0;
                        }
                    }
                    if(!$s){
                        $time = M('codes')->where("account = $tel and mtype = $mtype")->getField('addtime');
                        if($time){
                            $m = (time()-$time)/60;
                            if($m <= 1){
                                $s = 1;
                                $results = array(
                                    'status' => 1,
                                    'msg' => '请一分钟后再试',
                                );
                            }else{
                                $s = 0;
                            }
                        }
                        if(!$s){
                            $code = rand('100000', '999999');
                            $sms = send_checkcode($tel, $code);
                            $count = M('codes')->where("account = '$tel'")->count();
                            $data = array(
                                'account' => $tel,
                                'rand' => $code,
                                'mtype' => $mtype,
                                'state' => ($sms == '00') ? 0 : 1,
                                'addtime' => time(),
                                'sessid'=>$seid,
                                'ip'=>$ip
                            );
                            M("codes")->add($data);
                            if($sms == '00') {
                                $results = array(
                                    'status' => 0,
                                    'msg' => '发送成功'
                                );
                            }else {
                                $results = array(
                                    'status' => 1,
                                    'msg' => '发送失败'
                                );
                            }
                        }
                    }
                }
            }
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 验证短信验证码
     * @chenxuan
     * 2015-05-20
     */
    public function check_phone_bdsj_new(){
        $mobile = $_REQUEST['mobile'];
        $id = $_REQUEST['id'];
        $count = M('user')->where("phone = '".$mobile."' and id != ".$id)->count();
        $result = array(
            'status' => $count,
        );
        echo json_encode($result);
        exit;
    }

    /*
     * 验证短信验证码
     * @chenxuan
     * 2015-05-20
     */

    public function check_code() {
        $tel = $_REQUEST['tel'];
        $code = $_REQUEST['code'];
        $mtype = $_REQUEST['mtype'];
        $count = M('codes')->where("account = $tel and rand = $code and mtype = $mtype")->count();
        if ($count > 0) {
            $results = array(
                'status' => '00',
                'msg' => '验证成功'
            );
        } else {
            $results = array(
                'status' => '01',
                'msg' => '验证码不存在'
            );
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 注册
     * @chenxuan
     * 2015-05-20
     */

    public function regiest() {
        $name = $_REQUEST['name'];
        $pwd = $_REQUEST['pwd'];
        $channel = $_REQUEST['channel'];
        if(!$channel){
            $channel = 0;
        }
        if (empty($name) || empty($pwd)) {
            $results = array(
                'status' => '01',
                'msg' => '请求参数异常'
            );
            echo json_encode($results);
            exit;
        }
        $count = M('user')->where("phone=$name")->count();
        if ($count > 0) {
            $results = array(
                'status' => '01',
                'msg' => '用户已存在'
            );
            echo json_encode($results);
            exit;
        }
        $data = array(
            'name' => $name,
            'pwd' => md5($pwd),
            'phone' => $name,
            'addtime' => time(),
            'state' => 1,
            'channel'=>$channel
        );
        $id = M("user")->add($data);
        if($id){
            $user = M('user')->field('id,name,phone,email,avatar,money')->where("id=".$id)->find();
            $results = array(
                'status' => 0,
                'user'=>$user,
                'msg' => '注册成功'
            );
        }else{
            $results = array(
                'status' => 1,
                'user'=>$user,
                'msg' => '注册失败，请重新注册'
            );
        }
        echo json_encode($results);
        exit;
    }

    public function regiest2() {
        $name = $_REQUEST['name'];
        $pwd = $_REQUEST['pwd'];
        $channel = $_REQUEST['channel'];
        if(!$channel){
            $channel = 0;
        }
        if (empty($name) || empty($pwd)) {
            $results = array(
                'status' => 1,
                'msg' => '参数异常'
            );
            echo json_encode($results);
            exit;
        }
        $count = M("user")->where("phone=".$name)->count();
        if ($count > 0) {
            $results = array(
                'status' => 1,
                'msg' => '用户已存在'
            );
            echo json_encode($results);
            exit;
        }
        $data = array(
            'name' => $name,
            'pwd' => md5($pwd),
            'phone' => $name,
            'addtime' => time(),
            'state' => 1,
            'channel'=>$channel
        );
        $id = M("user")->add($data);
        if($id){
            $coupons = M("coupon")->where("flag = 1 and status = 1")->field("id,num")->select();
            foreach ($coupons as $coupon) {
                $coupon_id = $coupon['id'];
                $coupon_num = $coupon['num'];
                $uc_data = array(
                    'coupon_id'=>$coupon_id,
                    'user_id'=>$id,
                    'add_time'=>time(),
                    'status'=>0
                );
                $c_data = array(
                    'num'=>(intval($coupon_num)+1),
                );
                M("coupon_user")->add($uc_data);
                M("coupon")->where("id=".$coupon_id)->save($c_data);   
            }
            $results = array(
                'status' => 0,
                'user_id'=>$id,
                'msg' => '注册成功'
            );
        }else{
            $results = array(
                'status' => 1,
                'msg' => '注册失败'
            );
        }
        echo json_encode($results);
        exit;
    }

    public function regiest3() {
        $name = $_REQUEST['name'];
        $pwd = $_REQUEST['pwd'];
        $channel = $_REQUEST['channel'];
        $invite_id = $_REQUEST['invite_id'];
        $city_id = $_REQUEST['city_id'];
        if(!$channel){
            $channel = 0;
        }
        if (empty($name) || empty($pwd)) {
            $results = array(
                'status' => 1,
                'msg' => '参数异常'
            );
            echo json_encode($results);
            exit;
        }
        $count = M("user")->where("phone=".$name." and name != '' and is_check != 0")->count();
        if ($count > 0) {
            $results = array(
                'status' => 1,
                'msg' => '用户已存在'
            );
            echo json_encode($results);
            exit;
        }
        $data = array(
            'name' => $name,
            'pwd' => md5($pwd),
            'phone' => $name,
            'addtime' => time(),
            'state' => 1,
            'channel'=>$channel,
            'is_check'=>1,
            'invite_id'=>$invite_id,
            'area_id'=>$city_id,
            'area_id_r'=>$city_id
        );
        $id = M("user")->add($data);
        if($id){
            $coupons = M("coupon")->where("flag = 1 and status = 1")->field("id,num")->select();
            foreach ($coupons as $coupon) {
                $coupon_id = $coupon['id'];
                $coupon_num = $coupon['num'];
                $uc_data = array(
                    'coupon_id'=>$coupon_id,
                    'user_id'=>$id,
                    'add_time'=>time(),
                    'status'=>0
                );
                $c_data = array(
                    'num'=>(intval($coupon_num)+1),
                );
                M("coupon_user")->add($uc_data);
                M("coupon")->where("id=".$coupon_id)->save($c_data);   
            }
            $results = array(
                'status' => 0,
                'user_id'=>$id,
                'msg' => '注册成功'
            );
        }else{
            $results = array(
                'status' => 1,
                'msg' => '注册失败'
            );
        }
        echo json_encode($results);
        exit;
    }

    public function invite_login() {
        $name = $_REQUEST['phone'];
        $pwd = $_REQUEST['yzm'];
        $channel = $_REQUEST['channel'];
        $invite_id = $_REQUEST['id'];
        $city_id = $_REQUEST['city_id'];
        $ip = $_REQUEST['ip'];
        if(!$channel){
            $channel = 0;
        }
        if (empty($name) || empty($pwd)) {
            $results = array(
                'status' => 1,
                'msg' => '参数异常'
            );
            echo json_encode($results);
            exit;
        }
        $count = M("user")->where("phone = ".$name." and name != '' and is_check != 0")->count();
        if ($count > 0) {
            $results = array(
                'status' => 1,
                'msg' => '用户已存在'
            );
            echo json_encode($results);
            exit;
        }
        $is_away = M("area")->where("id = ".$city_id)->getField("is_away");
        if(!$is_away){
            $city_id = M("area")->where("is_away = 1 and level = 2 order by ord desc,id asc")->getField("id");
        }
        $shop_id_result = json_decode($this->getShopId2($city_id));
        $fruit_id = $shop_id_result['id_fruit'];
        $veg_id = $shop_id_result['id_veg'];
        $data = array(
            'name' => $name,
            'pwd' => md5($pwd),
            'phone' => $name,
            'addtime' => time(),
            'state' => 1,
            'channel'=>$channel,
            'is_check'=>1,
            'invite_id'=>$invite_id,
            'area_id'=>$city_id,
            'area_id_r'=>$city_id,
            'logintime'=>time(),
            'loginip'=>$ip,
        );
        $id = M("user")->add($data);
        if($id){
            $coupons = M("coupon")->where("flag = 1 and status = 1")->field("id,num")->select();
            foreach ($coupons as $coupon) {
                $coupon_id = $coupon['id'];
                $coupon_num = $coupon['num'];
                $uc_data = array(
                    'coupon_id'=>$coupon_id,
                    'user_id'=>$id,
                    'add_time'=>time(),
                    'status'=>0
                );
                $c_data = array(
                    'num'=>(intval($coupon_num)+1),
                );
                M("coupon_user")->add($uc_data);
                M("coupon")->where("id=".$coupon_id)->save($c_data);   
            }
            $results = array(
                'status' => 0,
                'user_id'=>$id,
                'city_id'=>$city_id,
                'fruit_id'=>$fruit_id,
                'veg_id'=>$veg_id,
                'msg' => '注册成功'
            );
        }else{
            $results = array(
                'status' => 1,
                'msg' => '注册失败'
            );
        }
        echo json_encode($results);
        exit;
    }

    public function checkOpenidWeixin(){
        $openid = $_REQUEST['openid'];
        $nickname = $_REQUEST['nickname'];
        $avatar = $_REQUEST['avatar'];
        $openid = trim($openid);
        $ip = $_REQUEST['ip'];
        $ip = trim($ip);
        $result = array();
        if(!$openid){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $user_id = M("user")->where("openid = '".$openid."' and is_check > 0 and phone != ''")->getField("id");
            if(!$user_id){
                $result['status'] = 2;
                $result['msg'] = "未注册/未绑定";
            }else{
                $data = array('logintime'=>time(),'loginip'=>$ip,'name'=>$nickname,'avatar'=>$avatar);
                $res = M("user")->where("id = ".$user_id)->save($data);
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "登录成功";
                    $result['user_id'] = $user_id;
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "登录失败";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function wxLogin(){
        $openid = $_REQUEST['openid'];
        $nickname = $_REQUEST['nickname'];
        $avatar = $_REQUEST['avatar'];
        $invite_id = $_REQUEST['invite_id'];
        $city_id = $_REQUEST['city_id'];
        $city = $_REQUEST['city'];
        $sex = $_REQUEST['sex'];
        $language = $_REQUEST['language'];
        $openid = trim($openid);
        $ip = $_REQUEST['ip'];
        $ip = trim($ip);
        $result = array();
        if(!$openid){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $user_id = M("user")->where("openid = '".$openid."' and is_check > 0")->getField("id");
            if(!$user_id){
                $data = array('name'=>$nickname,'avatar'=>$avatar,'openid'=>$openid,'addtime'=>time(),'logintime'=>time(),'loginip'=>$ip,'invite_id'=>$invite_id,'is_check'=>1,'area_id_r'=>$city_id,'area_id'=>$city_id,'city'=>$city,'sex'=>$sex,'language'=>$language);
                $res = M("user")->add($data);
                $coupons = M("coupon")->where("flag = 1 and status = 1")->field("id,num")->select();
                foreach ($coupons as $coupon) {
                    $coupon_id = $coupon['id'];
                    $coupon_num = $coupon['num'];
                    $uc_data = array(
                        'coupon_id'=>$coupon_id,
                        'user_id'=>$res,
                        'add_time'=>time(),
                        'status'=>0
                    );
                    $c_data = array(
                        'num'=>(intval($coupon_num)+1),
                    );
                    M("coupon_user")->add($uc_data);
                    M("coupon")->where("id=".$coupon_id)->save($c_data);   
                }
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "登录成功";
                    $result['user_id'] = $res;
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "登录失败";
                }
            }else{
                $data = array('logintime'=>time(),'loginip'=>$ip,'name'=>$nickname,'avatar'=>$avatar);
                $res = M("user")->where("id = ".$user_id)->save($data);
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "登录成功";
                    $result['user_id'] = $user_id;
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "登录失败";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function regiest_weixin() {
        $name = $_REQUEST['name'];
        $channel = $_REQUEST['channel'];
        $city_id = $_REQUEST['city_id'];
        $openid = $_REQUEST['openid'];
        $avatar = $_REQUEST['avatar'];
        $city = $_REQUEST['city'];
        $sex = $_REQUEST['sex'];
        $language = $_REQUEST['language'];
        $phone = $_REQUEST['phone'];
        $bind_flag = $_REQUEST['bind_flag'];
        $ip = $_REQUEST['ip'];
        if(!$channel){
            $channel = 0;
        }
        if(empty($name) || empty($city_id) || empty($openid) || empty($phone)){
            $results = array(
                'status' => 1,
                'msg' => '参数异常'
            );
            echo json_encode($results);
            exit;
        }
        if($bind_flag){
            $pwd = $_REQUEST['bind_pwd'];
            $pwd = trim($pwd);
            if(!$pwd){
                $results = array(
                    'status' => 1,
                    'msg' => '参数异常'
                );
                echo json_encode($results);
                exit;
            }
            $pwd = md5($pwd);
            $user = M("user")->where("phone = '".$phone."' and pwd = '".$pwd."' and is_check > 0 and name != ''")->find();
            if($user){
                $user_data = array(
                    'name' => $name,
                    'openid'=>$openid,
                    'city'=>$city,
                    'language'=>$language,
                    'sex'=>$sex,
                    'avatar'=>$avatar,
                    'logintime'=>time(),
                    'loginip'=>$ip,
                );
                $res = M("user")->where("id = ".$user['id'])->save($user_data);
                if($res){
                    $results = array(
                        'status' => 0,
                        'msg' => '登录成功',
                        'user_id'=>$user['id'],
                    );
                }else{
                    $results = array(
                        'status' => 1,
                        'msg' => '绑定失败',
                    );
                }
            }else{
                $results = array(
                    'status' => 1,
                    'msg' => '参数异常',
                );
            }
        }else{
            $yzm = $_REQUEST['yzm'];
            $pwd = $_REQUEST['pwd'];
            $yzm = trim($yzm);
            $pwd = trim($pwd);
            if(!$yzm && !$pwd){
                $results = array(
                    'status' => 1,
                    'msg' => '参数异常'
                );
                echo json_encode($results);
                exit;
            }
            $count = M("codes")->where("account = '".$phone."' and rand = '".$yzm."'")->count();
            if(!$count){
                $results = array(
                    'status' => 1,
                    'msg' => '验证码错误'
                );
                echo json_encode($results);
                exit;
            }
            $user_id = M("user")->where("openid='".$openid."' and is_check = 1")->getField("id");
            if ($user_id){
                $data = array('logintime'=>time(),'loginip'=>$ip,'phone'=>$phone,'pwd'=>md5($pwd));
                $res = M("user")->where("id =".$user_id)->save($data);
                if($res){
                    $results = array(
                        'status' => 0,
                        'msg' => '登录成功',
                        'user_id'=>$user['id'],
                    );
                }else{
                    $results = array(
                        'status' => 1,
                        'msg' => '绑定失败',
                    );
                }
            }else{
                $data = array(
                    'name' => $name,
                    'addtime' => time(),
                    'state' => 1,
                    'channel'=>$channel,
                    'is_check'=>1,
                    'area_id'=>$city_id,
                    'area_id_r'=>$city_id,
                    'openid'=>$openid,
                    'city'=>$city,
                    'language'=>$language,
                    'sex'=>$sex,
                    'avatar'=>$avatar,
                    'logintime'=>time(),
                    'loginip'=>$ip,
                    'phone'=>$phone,
                    'pwd'=>md5($pwd),
                );
                $id = M("user")->add($data);
                if($id){
                    $coupons = M("coupon")->where("flag = 1 and status = 1")->field("id,num")->select();
                    foreach ($coupons as $coupon) {
                        $coupon_id = $coupon['id'];
                        $coupon_num = $coupon['num'];
                        $uc_data = array(
                            'coupon_id'=>$coupon_id,
                            'user_id'=>$id,
                            'add_time'=>time(),
                            'status'=>0
                        );
                        $c_data = array(
                            'num'=>(intval($coupon_num)+1),
                        );
                        M("coupon_user")->add($uc_data);
                        M("coupon")->where("id=".$coupon_id)->save($c_data);   
                    }
                    $results = array(
                        'status' => 0,
                        'user_id'=>$id,
                        'msg' => '登录成功'
                    );
                }else{
                    $results = array(
                        'status' => 1,
                        'msg' => '注册失败'
                    );
                }
            }
        }
        echo json_encode($results);
        exit;
    }

    public function checkUserPhone(){
        $user_id = $_REQUEST['user_id'];
        $phone = M("user")->where("id = ".$user_id)->getField("phone");
        $result = array();
        if($phone){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['is_phone'] = 1;
        }else{
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['is_phone'] = 0;
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 用户签到
     * @queyuan
     * 2015-08-14
     */
    public function user_sign(){
        $user_id = $_REQUEST['user_id'];
        $user = M("user")->where("id = ".$user_id)->find();
        $result = array();
        if(!$user){
            $result['status'] = 1;
            $result['msg'] = "无此用户";
        }else{
            $user_sign = M("user_sign")->where("user_id = ".$user_id)->find();
            if($user_sign){
                $time = $user_sign['sign_time'];
                $time_str = date("Y-n-j",$time);
                $notime_str = date("Y-n-j",time());
                if($time_str == $notime_str){
                    $result['status'] = 1;
                    $result['msg'] = "今日已签";
                }else{
                    $num = $user_sign['num'];
                    $num = intval($num)+1;
                    $data = array('sign_time'=>time(),'num'=>$num);
                    $res = M("user_sign")->where("id = ".$user_sign['id'])->save($data);
                    $integral = $user['integral'];
                    $integral = intval($integral)+10;
                    $u_data = array("integral"=>$integral);
                    M("user")->where("id = ".$user_id)->save($u_data);
                    if($res){
                        $result['status'] = 0;
                        $result['msg'] = "签到成功";
                    }
                }
            }else{
                $data = array("sign_time"=>time(),"user_id"=>$user_id);
                $res = M("user_sign")->add($data);
                $integral = $user['integral'];
                $integral = intval($integral)+10;
                $u_data = array("integral"=>$integral);
                M("user")->where("id = ".$user_id)->save($u_data);
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "签到成功";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function check_sign(){
        $user_id = $_REQUEST['user_id'];
        $user = M("user")->where("id = ".$user_id)->find();
        $result = array();
        if(!$user){
            $result['status'] = 1;
            $result['msg'] = "无此用户";
        }else{
            $user_sign = M("user_sign")->where("user_id = ".$user_id)->find();
            if($user_sign){
                $time = $user_sign["sign_time"];
                $time_str = date("Y-n-j",$time);
                $notime_str = date("Y-n-j",time());
                if($time_str == $notime_str){
                    $result['status'] = 1;
                    $result['msg'] = "今日已签";
                }else{
                    $result['status'] = 0;
                    $result['msg'] = "今日未签";
                }
            }else{
                $result['status'] = 0;
                $result['msg'] = "今日未签";
            }
        }
        echo json_encode($result);
    }

    public function get_coupon(){
        $user_id = $_REQUEST['user_id'];
        $id = $_REQUEST['id'];
        $coupon = M("coupon")->where("id = ".$id." and flag = 0 and status = 1")->find();
        $user = M("user")->where("id = ".$user_id)->find();
        $result = array();
        if(!$user){
            $result['status'] = 1;
            $result['msg'] = "无此用户";
        }else{
            if(!$coupon){
                $result['status'] = 1;
                $result['msg'] = "无此红包";
            }else{
                $deadline = $coupon['deadline'];
                if($deadline){
                    if($deadline < time()){
                        $result['status'] = 1;
                        $result['msg'] = "红包已过期";
                    }else{
                        if(intval($user['integral']) >= intval($coupon['value'])){
                            $deadline = 0;
                            if($coupon['use_deadline'] == 0){
                                $deadline = 0;
                            }elseif($coupon['use_deadline'] == 1){
                                $deadline = strtotime("+1 weeks");
                            }elseif($coupon['use_deadline'] == 2){
                                $deadline = strtotime("+1 months");
                            }elseif($coupon['use_deadline'] == 3){
                                $deadline = strtotime("+1 years");
                            }
                            $data = array('coupon_id'=>$id,'user_id'=>$user_id,'add_time'=>time(),'status'=>0,'deadline'=>$deadline);
                            $res = M("coupon_user")->add($data);
                            $u_data = array('integral'=>(intval($user['integral'])-intval($coupon['value'])));
                            M("user")->where("id = ".$user_id)->save($u_data);
                            if($res){
                                $result['status'] = 0;
                                $result['msg'] = "兑换成功";
                            }else{
                                $result['status'] = 1;
                                $result['msg'] = "兑换失败";
                            }
                        }else{
                            $result['status'] = 1;
                            $result['msg'] = "积分不足";
                        }
                    }
                }else{
                    if(intval($user['integral'])>= intval($coupon['value'])){
                        $data = array('coupon_id'=>$id,'user_id'=>$user_id,'add_time'=>time(),'status'=>0);
                        $res = M("coupon_user")->add($data);
                        $u_data = array('integral'=>(intval($user['integral'])-intval($coupon['value'])));
                        M("user")->where("id = ".$user_id)->save($u_data);
                        if($res){
                            $result['status'] = 0;
                            $result['msg'] = "兑换成功";
                        }else{
                            $result['status'] = 1;
                            $result['msg'] = "兑换失败";
                        }
                    }else{
                        $result['status'] = 1;
                        $result['msg'] = "积分不足";
                    }
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 查询用户信息
     * @queyuan
     * 2015-08-14
     */
    public function getUser(){
        $user_id = $_REQUEST['user_id'];
        $user = M("user")->where("id = ".$user_id)->field("id,name,phone,email,avatar,money,integral,is_check")->find();
        if($user){
        	if(!$user['money']){
        		$user['money'] = "0";
        	}
            $result = array(
                'status'=>0,
                'msg'=>"请求成功",
                'user'=>$user,
            );
        }else{
            $result = array(
                'status'=>1,
                'msg'=>"无此用户",
            );
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 修改绑定手机号码
     * @chenxuan
     * 2015-05-20
     */

    public function edit_phone() {
        $phone = $_REQUEST['phone'];
        $oldphone = $_REQUEST['oldphone'];
        $uid = $_REQUEST['uid'];
        $count = M('user')->where("id=$uid and phone=$oldphone")->count();
        if ($count == 0) {
            $results = array(
                'status' => '01',
                'msg' => '原手机号码不正确'
            );
            echo json_encode($results);
            exit;
        }
        $data = array('phone' => $phone);
        M('user')->where("id=$uid and phone=$oldphone")->save($data);
        $results = array(
            'status' => '00',
            'msg' => '修改成功'
        );
        echo json_encode($results);
        exit;
    }

    /*
     * 找回密码
     * @chenxuan
     * 2015-05-20
     */

    public function find_password() {
        $phone = $_REQUEST['phone'];
        $password = $_REQUEST['password'];
        $count = M('user')->where("phone = $phone")->count();
        echo $count;
        exit;
        if ($count == 0) {
            $results = array(
                'status' => '01',
                'msg' => '用户不存在'
            );
            echo json_encode($results);
            exit;
        }
        $data = array('pwd' => $password);
        M('user')->where("phone=$phone")->save($data);
        $results = array(
            'status' => '00',
            'msg' => '找回密码成功'
        );
        echo json_encode($results);
        exit;
    }

    /*
     * 每日浏览
     * @chenxuan
     * 2015-05-22
     */

    public function browse() {
        $uid = $_REQUEST['uid'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        //今日时间
        $date = date('Y-m-d', time());
        $strat_date = strtotime($date . " 00:00:00");
        $end_date = strtotime($date . " 23:59:59");
        $sql = " browse_time > $strat_date and browse_time < $end_date";
        if ($uid) {
            $sql .= " and user_id = $uid";
        } else {
            $results = array(
                'status' => '01',
                'msg' => "参数异常"
            );
            echo json_encode($results);
            exit;
        }
        $count = M("daily_browse")->where($sql)->count();
        if ($count > 0) {
            if (empty($pagesizes)) {
                $pagesizes = 10;
            }
            if (empty($startrow)) {
                $startrow = 0;
            } else {
                $startrow = $startrow * $pagesizes;
            }
            $browse = M("daily_browse")->where($sql)->limit($startrow . ',' . $pagesizes)->order('browse_time desc')->select();
            foreach ($browse as &$val) {
                $val['goods'] = M('goods')->where("id=" . $val['goods_id'])->find();
                $val['goods']['cat_name'] = M('goods_cat')->where("id=$lists[cat_id]")->getField('name');
                $val['goods']['unit_name'] = M('dictionary')->where("id=$lists[unit]")->getField('name');
            }
            $results = array(
                'status' => '00',
                'data' => array(
                    'total' => $count,
                    'rows' => $browse
                )
            );
        } else {
            $results = array(
                'status' => '00',
                'data' => array(
                    'total' => $count,
                    'rows' => array()
                )
            );
        }
        echo json_encode($results);
        exit;
    }

    /*
     * 浏览添加
     * @chenxuan
     * 2015-05-22
     */

    public function browse_add() {
        $uid = $_REQUEST['uid'];
        $shop_id = $_REQUEST['shop_id'];
        $goods_id = $_REQUEST['goods_id'];
        $type = $_REQUEST['type'];
        if ($uid && $shop_id && $goods_id && $type) {
            $data = array(
                'user_id' => $uid,
                'shop_id' => $shop_id,
                'goods_id' => $goods_id,
                'type' => $type,
                'browse_time' => time()
            );
            M('daily_browse')->add($data);
            $results = array(
                'status' => '00',
                'msg' => "添加成功"
            );
            echo json_encode($results);
            exit;
        } else {
            $results = array(
                'status' => '01',
                'msg' => "参数异常"
            );
            echo json_encode($results);
            exit;
        }
    }

    /*
     * 团购购物车
     * @chenxuan
     * 2015-05-22
     */

    public function tuan_cart() {
        $uid = $_REQUEST['uid'];
        $startrow = $_REQUEST['startrow'];
        $pagesizes = $_REQUEST['pagesizes'];
        $sql = "1";
        if ($uid) {
            $sql .= " and user_id = $uid";
        } else {
            $results = array(
                'status' => '01',
                'msg' => "参数异常"
            );
            echo json_encode($results);
            exit;
        }
        $count = M("tuan_cart")->where($sql)->count();
        if ($count > 0) {
            if (empty($pagesizes)) {
                $pagesizes = 10;
            }
            if (empty($startrow)) {
                $startrow = 0;
            } else {
                $startrow = $startrow * $pagesizes;
            }
            $cart = M("tuan_cart")->where($sql)->limit($startrow . ',' . $pagesizes)->order('browse_time desc')->select();
            foreach ($cart as &$val) {
                $val['goods'] = M('goods')->where("id=" . $val['goods_id'])->find();
            }
            $results = array(
                'status' => '00',
                'data' => array(
                    'total' => $count,
                    'rows' => $cart
                )
            );
        } else {
            $results = array(
                'status' => '00',
                'data' => array(
                    'total' => $count,
                    'rows' => array()
                )
            );
        }
        echo json_encode($results);
        exit;
    }

    /**
     * 外送点单加入购物车
     * @queyuan
     * 2015-08-01
     */
    public function add_dish_cart(){
        $user_id = $_REQUEST['user_id'];
        $dish_id = $_REQUEST['dish_id'];
        $flag = $_REQUEST['flag'];
        $result = array();
        if($user_id && $dish_id){
            $res = M("shop_dishes")->where("id = ".$dish_id)->field("price,shop_id")->find();
            $shop_id = $res['shop_id'];
            $unit_price = $res['price'];
            if($shop_id && $unit_price){
                $cres = M("dish_cart")->where("user_id = ".$user_id." and dish_id = ".$dish_id." and shop_id = ".$shop_id." and status = 0")->field("id,amount")->find();
                $amount = $cres['amount'];
                $id = $cres['id'];
                if($id){
                    $data['updatetime'] = time();
                    if($flag){
                        $data['amount'] = intval($amount) + 1;
                    }else{
                        if($amount > 0){
                            $data['amount'] = intval($amount) - 1;
                        }                    
                    }
                }else{
                    if($flag){
                        $data['amount'] = 1;
                    }else{
                        if($amount > 0){
                            $data['amount'] = 0;
                        }                    
                    }
                    $data['user_id'] = $user_id;
                    $data['shop_id'] = $shop_id;
                    $data['dish_id'] = $dish_id;
                    $data['status'] = 0;
                    $data['addtime'] = time();
                    $data['updatetime'] = time();
                    $data['unit_price'] = $unit_price;
                }
                if($id){
                    $r = M("dish_cart")->where("id = ".$id)->save($data);
                }else{
                    $r = M("dish_cart")->add($data);
                }
                $res2 = M("dish_cart")->field("sum(amount*unit_price) as total_price")->where("user_id = ".$user_id." and status = 0")->find();
                $total_price = $res2['total_price'];
                $count = M("dish_cart")->where("user_id = ".$user_id." and dish_id = ".$dish_id." and status = 0")->getField("amount");
                if($r){
                    $result['status'] = 0;
                    $result['msg'] = "添加成功";
                    $result['total_price'] = $total_price;
                    $result['count'] = $count;
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "请求失败";
                    $result['total_price'] = $total_price;
                    $result['count'] = $count;
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "参数异常";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 用户参团
     * @queyuan
     * 2016/04/09
     * @param id——订单ID
     * @param user_id——用户ID
     */
    public function join_tuan(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $order = M("away_order o")->join("left join meal_away_order_goods g on (g.order_id = o.id)")->where("o.id =".$id)->field("o.id,o.total_price,g.shop_id.g.goods_id,g.goods_name,g.unit_price,g.amount,g.gg_id")->find();
        $receive = M("user_receive")->where("uid = ".$user_id." and is_default = 1")->find();
        do{
            $order_sn = $this->get_order_sn();
            break;
        }while(check_away_order($order_sn) > 0);
        $order_data = array();
        $order_data['order_sn'] = $order_sn;
        $order_data['user_id'] = $user_id;
        $order_data['order_id'] = $order['id'];
        $order_data['receive_id'] = $receive['id'];
        $order_data['phone'] = $receive['phone'];
        $order_data['circles'] = $receive['circles'];
        $order_data['address'] = $receive['address'];
        $order_data['realname'] = $receive['realname'];
        
    }

    public function edit_dish_cart(){
        $id = $_REQUEST['id'];
        $flag = $_REQUEST['flag'];
        $user_id = $_REQUEST['user_id'];
        $result = array();
        if($id){
            $amount = M("dish_cart")->where("id = ".$id)->getField("amount");
            $gg_id = M("dish_cart")->where("id=".$id)->getField("gg_id");
            $dish_id = M("dish_cart")->where("id=".$id)->getField("dish_id");
            $max_num = M("shop_dishes")->where("id=".$dish_id)->getField("active_max_num");
            if(!$gg_id && $flag){
                if(intval($amount) >= intval($max_num)){
                    $result['status'] = 1;
                    $result['msg'] = "已达上限";
                }
            }
            if(!$result['status']){
                $amount = intval($amount);
                if($flag){
                    $data['amount'] = $amount + 1;
                }else{
                    if($amount){
                        $data['amount'] = $amount - 1;
                    }else{
                        $data['amount'] = 0;
                    }
                }
                $res = M("dish_cart")->where("id=".$id)->save($data);
                $total_price = M("dish_cart c")->join("left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id)")->where("c.status = 0 and c.amount > 0 and c.user_id = ".$user_id." and d.is_out = 0")->getField("sum(c.unit_price * c.amount) as sum");
                $total_price_tuan = M("dish_cart c")->join("left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id)")->where("c.status = 0 and c.amount > 0 and c.user_id = ".$user_id." and d.is_out = 0")->getField("sum(g.price_tuan * c.amount) as sum");
                $count = M("dish_cart")->where("id = ".$id)->getField("amount");
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['total_price'] = $total_price;
                $result['total_price_tuan'] = $total_price_tuan;
                $result['count'] = $count;
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }
        echo json_encode($result);
        exit;
    }

    public function add_dish_cart2(){
        $user_id = $_REQUEST['user_id'];
        $dish_id = $_REQUEST['d_id'];
        $gg_id = $_REQUEST['g_id'];
        $am = intval($_REQUEST['amount']);
        $result = array();
        if($user_id && $dish_id && $am){
            if($gg_id){
                $res = M("dish_gg g")->join("left join meal_shop_dishes d on (g.dish_id = d.id)")->where("g.id = ".$gg_id)->field("g.price,d.shop_id,g.price_tuan,g.active_id")->find();
                if($res['active_id']){
                    $active = M("active_dishes")->where("id = ".$res['active_id'])->field("begintime,deadline")->find();
                    if($active['begintime'] > time()){
                        $result['status'] = 1;
                        $result['msg'] = "尚未开抢";
                        echo json_encode($result);
                        exit;
                    }elseif($active['deadline'] < time()){
                        $result['status'] = 1;
                        $result['msg'] = "已结束";
                        echo json_encode($result);
                        exit;
                    }
                }
                $unit_price = $res['price'];
                $unit_price_tuan = $res['price_tuan'];
                $shop_id = $res['shop_id'];
            }else{
                $res = M("shop_dishes")->where("id = ".$dish_id." and is_active = 1")->field("active_price,shop_id,active_max_num")->find();
                if($res){
                    $unit_price = $res['active_price'];
                    $unit_price_tuan = $res['active_price'];
                    $shop_id = $res['shop_id'];
                    $max_num = $res['active_max_num'];
                }
            }
            if($shop_id){
                $cres = M("dish_cart")->where("user_id = ".$user_id." and dish_id = ".$dish_id." and shop_id = ".$shop_id." and status = 0 and gg_id = ".$gg_id)->field("id,amount")->find();
                $amount = $cres['amount'];
                if(!$gg_id){
                    if($amount >= $max_num){
                        $result['status'] = 1;
                        $result['msg'] = "已达上限";
                    }
                }
                if(!$result['status']){
                    $id = $cres['id'];
                    if($id){
                        $data['updatetime'] = time();
                        $data['amount'] = intval($amount) + $am;
                        $data['unit_price'] = $unit_price;
                        $data['unit_price_tuan'] = $unit_price_tuan;
                    }else{
                        $data['amount'] = $am;
                        $data['user_id'] = $user_id;
                        $data['shop_id'] = $shop_id;
                        $data['dish_id'] = $dish_id;
                        $data['gg_id'] = $gg_id;
                        $data['status'] = 0;
                        $data['addtime'] = time();
                        $data['updatetime'] = time();
                        $data['unit_price'] = $unit_price;
                        $data['unit_price_tuan'] = $unit_price_tuan;
                    }
                    if($id){
                        $r = M("dish_cart")->where("id = ".$id)->save($data);
                    }else{
                        $r = M("dish_cart")->add($data);
                    }
                    if($r){
                        $result['status'] = 0;
                        $result['msg'] = "已添加";
                    }else{
                        $result['status'] = 1;
                        $result['msg'] = "添加失败";
                    }
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "参数异常";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取外送购物车
     * @queyuan
     * 2015/08/02
     */
    public function get_dish_cart(){
        $user_id = $_REQUEST['user_id'];
        $sql = "c.status = 0 and c.amount > 0";
        $field = "c.dish_id,c.amount,(c.unit_price*c.amount) as total_price,d.name";
        $result = array();
        if($user_id){
            $sql .= " and c.user_id = ".$user_id;
            $carts = M("dish_cart c")->join("left join meal_shop_dishes d on (c.dish_id = d.id)")->where($sql)->field($field)->order("c.addtime,c.updatetime desc")->select();
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['carts'] = $carts;
        }else{
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 团购加入购物车
     * @chenxuan
     * 2015-05-22
     */

    public function add_tuan_cart() {
        $uid = $_REQUEST['uid'];
        $goods_id = $_REQUEST['goods_id'];
        $amount = $_REQUEST['amount'];
        if ($uid && $goods_id && $amount) {
            $goods = M('goods')->where("id=$goods_id")->find();
            $data = array(
                'user_id' => $uid,
                'goods_id' => $goods_id,
                'amount' => $amount,
                'shop_name' => M('shop')->where("id=" . $goods['sid'])->getField('name'),
                'shop_id' => $goods['sid'],
                'goods_name' => $goods['name'],
                'unit_price' => $goods['price']
            );
            M('tuan_cart')->add($data);
            $results = array(
                'status' => '00',
                'msg' => "加入购物车成功"
            );
            echo json_encode($results);
            exit;
        } else {
            $results = array(
                'status' => '01',
                'msg' => "参数异常"
            );
            echo json_encode($results);
            exit;
        }
    }

    /*
     * 修改团购购物车商品
     * @chenxuan
     * 2015-05-20
     */

    public function edit_tuan_cart() {
        $id = $_REQUEST['id'];
        $amount = $_REQUEST['amount'];
        if ($id && $amount) {
            $data = array('amount' => $amount);
            M('tuan_cart')->where("id = $id")->save($data);
            $results = array(
                'status' => '00',
                'msg' => "修改成功"
            );
            echo json_encode($results);
            exit;
        } else {
            $results = array(
                'status' => '01',
                'msg' => "参数异常"
            );
            echo json_encode($results);
            exit;
        }
    }

    public function get_away_order_bysn(){
        $order_sn = $_REQUEST['order_sn'];
        $order = M("away_order")->where("order_sn = '".$order_sn."'")->find();
        $result = array();
        if($order){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['order'] = $order;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无此订单";
        }
        echo json_encode($result);
        exit;
    }

    public function get_away_order(){
        $id = $_REQUEST['id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $order = M("away_order")->where("id = ".$id)->field("id,order_sn,total_price,order_time,flag,address,realname,memo,phone,is_tuan")->find();
            $order['s'] = strlen($order['order_sn']);
            if(!$order){
                $result['status'] = 1;
                $result['msg'] = "无此订单";
            }else{
                $dishes = M("away_order_goods g")->join("left join meal_away_order o on (g.order_id = o.id) left join meal_shop_dishes d on (g.goods_id = d.id) left join meal_dish_unit u on (d.unitid = u.id)")->field("d.name,d.price,u.name,g.amount,(g.amount*d.price) as total_price,d.amount as count,g.goods_name")->where("g.order_id=".$id)->select();
                $order['dishes'] = $dishes;
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['order'] = $order;
            }
        }
        echo json_encode($result);
        exit;
    }

    public function get_away_order2(){
        $id = $_REQUEST['id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $order = M("away_order")->where("id = ".$id)->field("id,order_sn,total_price,order_time,flag,address,realname,memo,phone,receive_id,status,circles")->find();
            $order['s'] = strlen($order['order_sn']);
            if(!$order){
                $result['status'] = 1;
                $result['msg'] = "无此订单";
            }else{
                $c_arr = explode(",",$order['circles']);
                $cir_arr = array();
                foreach ($c_arr as $c) {
                    $cir_arr[] = M("area")->where("id = ".$c)->getField("name");
                }
                $order['circles'] = implode(" ",$cir_arr);
                $order['phone'] = substr_replace($order['phone'],'*****',3,4);
                $dishes = M("away_order_goods g")->join("left join meal_away_order o on (g.order_id = o.id) left join meal_shop_dishes d on (g.goods_id = d.id) left join meal_dish_gg u on (g.gg_id = u.id)")->field("d.is_out,d.name,g.unit_price,u.gg,g.amount,(g.amount*g.unit_price) as total_price,d.amount as count,g.goods_name,d.img,d.shop_id")->where("g.order_id=".$id)->select();
                $order['is_out'] = M("away_order_goods g")->join("left join meal_away_order o on (g.order_id = o.id) left join meal_shop_dishes d on (g.goods_id = d.id) left join meal_dish_gg u on (g.gg_id = u.id)")->where("d.is_out = 1 and g.order_id = ".$id)->count();
                $order['dishes'] = $dishes;
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['order'] = $order;
            }
        }
        echo json_encode($result);
        exit;
    }

    public function get_away_order3(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $result = array();
        if(!$id){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $order = M("away_order o")->join("left join meal_away_order_goods g on (g.order_id = o.id) left join meal_dish_gg gg on (g.gg_id = gg.id)")->where("o.id = ".$id)->field("o.id,o.order_sn,o.total_price,o.order_time,o.flag,o.address,o.realname,o.memo,o.phone,o.receive_id,o.status,o.circles,gg.member,o.user_id,o.order_id")->find();
            if($user_id){
                if($order['user_id'] != $user_id){
                    $order2 = M("away_order o")->join("left join meal_away_order_goods g on (g.order_id = o.id) left join meal_dish_gg gg on (g.gg_id = gg.id)")->where("o.order_id = ".$id." and o.user_id = ".$user_id)->field("o.id,o.order_sn,o.total_price,o.order_time,o.flag,o.address,o.realname,o.memo,o.phone,o.receive_id,o.status,o.circles,gg.member,o.user_id,o.order_id")->find();
                    if($order2){
                        $order = $order2;
                    }
                }
            }
            if($order['order_id']){
                $count = M("away_order")->where("order_id = ".$order['order_id']." and status > 0 and status < 4")->count();
                $order['count'] = $count + 1;
                $users = array();
                $users[] = M("user u")->join("left join meal_away_order o on (o.user_id = u.id)")->where("o.id = ".$order['order_id'])->field("u.id,u.name,u.avatar")->find();
                $orders = M("away_order")->where("order_id = ".$order['order_id']." and status > 0 and status < 4")->order("pay_time asc")->field("user_id")->select();
                foreach ($orders as $order_item) {
                    $users[] = M("user")->where("id = ".$order_item['user_id'])->field("id,name,avatar")->find();
                }
                $order['users'] = $users;
            }else{
                $count = M("away_order")->where("order_id = ".$order['id']." and status > 0 and status < 4")->count();
                $order['count'] = $count + 1;
                $users = array();
                $users[] =M("user")->where("id = ".$order['user_id'])->field("id,name,avatar")->find();
                $orders = M("away_order")->where("order_id = ".$order['id']." and status > 0 and status < 4")->order("pay_time asc")->field("user_id")->select();
                foreach ($orders as $order_item) {
                    $users[] = M("user")->where("id = ".$order_item['user_id'])->field("id,name,avatar")->find();
                }
                $order['users'] = $users;
            }
            $order['s'] = strlen($order['order_sn']);
            if(!$order){
                $result['status'] = 1;
                $result['msg'] = "无此订单";
            }else{
                $c_arr = explode(",",$order['circles']);
                $cir_arr = array();
                foreach ($c_arr as $c) {
                    $cir_arr[] = M("area")->where("id = ".$c)->getField("name");
                }
                $order['circles'] = implode(" ",$cir_arr);
                $order['phone'] = substr_replace($order['phone'],'*****',3,4);
                $dishes = M("away_order_goods g")->join("left join meal_away_order o on (g.order_id = o.id) left join meal_shop_dishes d on (g.goods_id = d.id) left join meal_dish_gg u on (g.gg_id = u.id)")->field("d.is_out,d.name,g.unit_price,u.gg,g.amount,(g.amount*g.unit_price) as total_price,d.amount as count,g.goods_name,d.img,d.shop_id,d.id as dish_id")->where("g.order_id=".$id)->select();
                $order['is_out'] = M("away_order_goods g")->join("left join meal_away_order o on (g.order_id = o.id) left join meal_shop_dishes d on (g.goods_id = d.id) left join meal_dish_gg u on (g.gg_id = u.id)")->where("d.is_out = 1 and g.order_id = ".$id)->count();
                $order['dishes'] = $dishes;
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['order'] = $order;
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 提交外卖订单
     * @queyuan
     * 2015-08-05
     */
    public function add_away_order(){
        $result = array();
        $user_id = $_REQUEST['user_id'];
        $flag = $_REQUEST['flag'];
        //18660775093,
        $no_allow = "13053696500,18678330755,15154132468,18668991717,13165313443,18366172993,18264187585,18364149213,18366128421,18206410562,13573197416,13553173739,13589028563,15662622712,18954139161,18364196730,15098946681,13655310661,18405319092,18396897802,13370535021,15253116125,15554126195,13406959073,15894464446,18353128019,13075336092,15562590591,18769779479,15194197016,18753166379,18013873759,15806623793,15726120501,15169170259";
        $user = M("user")->where("id = ".$user_id." and phone not in (".$no_allow.")")->find();
        if($user){
            $dishes = M("dish_cart c")->join('left join meal_shop_dishes d on (c.dish_id = d.id)')->where("c.status=0 and c.user_id=".$user_id." and c.amount > 0")->field("c.id,c.shop_id,c.dish_id,c.amount,c.unit_price,d.name")->select();
            if($dishes){
                $total_price = M("dish_cart")->where("status=0 and user_id=".$user_id)->getField("sum(unit_price*amount) as sum");
                if($total_price < 68){
                    $result['status'] = 1;
                    $result['msg'] = '满68元起送';
                }else{
                    do {
                        $order_sn = $this->get_order_sn();
                        break;
                    } while (check_tuan_order($order_sn) > 0);
                    $order_data = array(
                        'order_sn' => $order_sn,
                        'user_id' => $user_id,
                        'total_price' => $total_price,
                        'order_time' => time(),
                        'status' => 0,
                        'flag' => $flag,
                    );
                    $cart_data = array('status'=>1);
                    $order_id = M("away_order")->add($order_data);
                    if($order_id){
                        $ids = array();
                        foreach ($dishes as $dish) {
                            $dish_data = array(
                                'order_id'=>$order_id,
                                'shop_id'=>$dish['shop_id'],
                                'goods_id'=>$dish['dish_id'],
                                'unit_price'=>$dish['unit_price'],
                                'amount'=>$dish['amount'],
                                'goods_name'=>$dish['name'],
                            );
                            $res = M("away_order_goods")->add($dish_data);
                            if($res){
                                $ids[] = $dish['id'];
                            }
                        }
                        $ids_str = implode(",",$ids);
                        $r = M("dish_cart")->where("id in (".$ids_str.")")->save($cart_data);
                        $result['status'] = 0;
                        $result['msg'] = "下单成功";
                        $result['id'] = $order_id;
                    }else{
                        $result['status'] = 1;
                        $result['msg'] = "下单失败";
                    }
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "购物车无商品";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "账号锁定";
        }
        echo json_encode($result);
        exit;
    }

    public function tuan_add(){
        $result = array();
        $user_id = $_REQUEST['user_id'];
        $dish_id = $_REQUEST['dish_id'];
        $city_id = $_REQUEST['city_id'];
        if(!$user_id || !$dish_id){
            $result['status'] = 1;
            $result['msg'] = "参数错误";
        }else{
            $dish = M("shop_dishes")->where("id = ".$dish_id)->find();
            $gg = M("dish_gg")->where("dish_id = ".$dish_id." and status = 1 and is_tuan = 1")->find();
            if(!$gg){
                $result['status'] = 1;
                $result['msg'] = "该产品无拼团";
            }else{
                do {
                    $order_sn = $this->get_order_sn();
                    break;
                }while(check_tuan_order($order_sn) > 0);
                $receives = M("user_receive")->where("uid = ".$user_id." and status = 1 and circles like '%,".$city_id.",%'")->order("is_default desc,id desc")->find();
                $order_data = array(
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'total_price' => $gg['price'],
                    'order_time' => time(),
                    'status' => 0,
                    'flag' => 0,
                    'is_tuan'=>1,
                );
                if($receives){
                    $order_data['receive_id'] = $receives['id'];
                    $order_data['phone'] = $receives['phone'];
                    $order_data['circles'] = $receives['circles'];
                    $order_data['address'] = $receives['address'];
                    $order_data['realname'] = $receives['realname'];
                }
                $goods_data = array(
                    'shop_id'=>$dish['shop_id'],
                    'goods_id'=>$dish_id,
                    'amount'=>1,
                    'goods_name'=>$dish['name'],
                    'unit_price'=>$gg['price'],
                    'gg_id'=>$gg['id'],
                );
                $order_id = M("away_order")->add($order_data);
                if(!$order_id){
                    $result['status'] = 1;
                    $result['msg'] = "下单失败";
                }else{
                    $goods_data['order_id'] = $order_id;
                    $res = M("away_order_goods")->add($goods_data);
                    $result['status'] = 0;
                    $result['msg'] = "下单成功";
                    $result['order_id'] = $order_id;
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    public function add_away_order2(){
        $result = array();
        $user_id = $_REQUEST['user_id'];
        $flag = $_REQUEST['flag'];
        $tuan = $_REQUEST['tuan'];
        if(!$tuan){
            $tuan = 0;
        }
        $no_allow = "13053696500,18678330755,15154132468,18668991717,13165313443,18366172993,18264187585,18364149213,18366128421,18206410562,13573197416,13553173739,13589028563,15662622712,18954139161,18364196730,15098946681,13655310661,18405319092,18396897802,13370535021,15253116125,15554126195,13406959073,15894464446,18353128019,13075336092,15562590591,18769779479,15194197016,18753166379,18660775093,18013873759,15806623793,15726120501,15169170259";
        $user = M("user")->where("id = ".$user_id." and phone not in (".$no_allow.")")->find();
        if($user){
            $dishes = M("dish_cart c")->join('left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id)')->where("c.status=0 and c.user_id=".$user_id." and c.amount > 0 and c.gg_id > 0 and d.is_out = 0")->field("c.id,c.shop_id,c.dish_id,c.amount,g.price as unit_price,d.name,c.gg_id,g.price_tuan")->select();
            if($dishes){
                if($tuan){
                    $total_price = M("dish_cart c")->join("left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id)")->where("c.status=0 and c.user_id=".$user_id." and c.gg_id > 0 and d.is_out = 0")->getField("sum(g.price_tuan*c.amount) as sum");
                }else{
                    $total_price = M("dish_cart c")->join("left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id)")->where("c.status=0 and c.user_id=".$user_id." and c.gg_id > 0 and d.is_out = 0")->getField("sum(g.price*c.amount) as sum");
                }
                if($total_price < 68){
                    $result['status'] = 1;
                    $result['msg'] = '满68元起送';
                }else{
                    do {
                        $order_sn = $this->get_order_sn();
                        break;
                    } while (check_tuan_order($order_sn) > 0);
                    $order_data = array(
                        'order_sn' => $order_sn,
                        'user_id' => $user_id,
                        'total_price' => $total_price,
                        'order_time' => time(),
                        'status' => 0,
                        'flag' => $flag,
                        'is_tuan'=>$tuan,
                    );
                    $cart_data = array('status'=>1);
                    $order_id = M("away_order")->add($order_data);
                    if($order_id){
                        $ids = array();
                        foreach ($dishes as $dish) {
                            $dish_data = array(
                                'order_id'=>$order_id,
                                'shop_id'=>$dish['shop_id'],
                                'goods_id'=>$dish['dish_id'],
                                'amount'=>$dish['amount'],
                                'goods_name'=>$dish['name'],
                                'gg_id'=>$dish['gg_id']
                            );
                            if($tuan){
                                $dish_data['unit_price'] = $dish['price_tuan'];
                            }else{
                                $dish_data['unit_price'] = $dish['unit_price'];
                            }
                            $res = M("away_order_goods")->add($dish_data);
                            if($res){
                                $ids[] = $dish['id'];
                            }
                        }
                        $ids_str = implode(",",$ids);
                        $r = M("dish_cart")->where("id in (".$ids_str.")")->save($cart_data);
                        $result['status'] = 0;
                        $result['msg'] = "下单成功";
                        $result['id'] = $order_id;
                    }else{
                        $result['status'] = 1;
                        $result['msg'] = "下单失败";
                    }
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "购物车无商品";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "账号锁定";
        }
        echo json_encode($result);
        exit;
    }

    public function add_away_order3(){
        $result = array();
        $user_id = $_REQUEST['user_id'];
        $flag = $_REQUEST['flag'];
        $no_check = $_REQUEST['no_check'];
        $city_id = $_REQUEST['city_id'];
        $no_arr = explode(",",$no_check);
        $noarr = array();
        //18660775093,
        $no_allow = "13053696500,18678330755,15154132468,18668991717,13165313443,18366172993,18264187585,18364149213,18366128421,18206410562,13573197416,13553173739,13589028563,15662622712,18954139161,18364196730,15098946681,13655310661,18405319092,18396897802,13370535021,15253116125,15554126195,13406959073,15894464446,18353128019,13075336092,15562590591,15194197016,18753166379,18013873759,15806623793,15726120501,15169170259";
        $user = M("user")->where("id = ".$user_id." and phone not in (".$no_allow.")")->find();
        if($user){
            foreach ($no_arr as $no) {
                if($no){
                    $noarr[] = $no;
                }
            }
            if($noarr){
                $no_check = implode(",",$noarr);
            }else{
                $no_check = "0";
            }
            $send_line = M("area")->where("id = ".$city_id)->getField("send_line");
            $dishes = M("dish_cart c")->join('left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_dish_gg g on (c.gg_id = g.id) left join meal_shop s on (d.shop_id = s.id)')->where("s.circles like '%,".$city_id.",%' and c.status=0 and c.user_id=".$user_id." and c.amount > 0 and d.is_out = 0 and (g.status != 0 or (c.gg_id = 0 and d.is_active = 1)) and c.id not in (".$no_check.")")->field("c.id,c.shop_id,c.dish_id,c.amount,c.unit_price,d.name,c.gg_id")->select();
            $receive = M("user_receive")->where("uid = ".$user_id." and status = 1 and circles like '%,".$city_id.",%'")->order("is_default desc")->field("id,realname,phone,address,circles")->find();
            if($dishes){
                $total_price = M("dish_cart c")->join("left join meal_dish_gg g on (c.gg_id = g.id) left join meal_shop_dishes d on (c.dish_id = d.id) left join meal_shop s on (d.shop_id = s.id)")->where("c.status = 0 and c.amount > 0 and c.user_id = ".$user_id." and d.is_out = 0 and s.circles like '%,".$city_id.",%' and ((c.gg_id > 0) or (c.gg_id = 0 and d.is_active = 1)) and (g.status != 0 or (c.gg_id = 0 and d.is_active = 1)) and c.id not in (".$no_check.")")->getField("sum(c.unit_price * c.amount) as sum");
                if($total_price < $send_line){
                    $result['status'] = 1;
                    $result['msg'] = '满'.$send_line.'元起送';
                }else{
                    do {
                        $order_sn = $this->get_order_sn();
                        break;
                    } while (check_away_order($order_sn) > 0);
                    $order_data = array(
                        'order_sn' => $order_sn,
                        'user_id' => $user_id,
                        'total_price' => $total_price,
                        'order_time' => time(),
                        'status' => 0,
                        'flag' => $flag,
                        'receive_id'=>$receive['id'],
                        'realname'=>$receive['realname'],
                        'circles'=>$receive['circles'],
                        'address'=>$receive['address'],
                        'phone'=>$receive['phone'],
                    );
                    $cart_data = array('status'=>1);
                    $order_id = M("away_order")->add($order_data);
                    if($order_id){
                        $ids = array();
                        foreach ($dishes as $dish) {
                            $dish_data = array(
                                'order_id'=>$order_id,
                                'shop_id'=>$dish['shop_id'],
                                'goods_id'=>$dish['dish_id'],
                                'amount'=>$dish['amount'],
                                'goods_name'=>$dish['name'],
                                'gg_id'=>$dish['gg_id']
                            );
                            $dish_data['unit_price'] = $dish['unit_price'];
                            $res = M("away_order_goods")->add($dish_data);
                            if($res){
                                $ids[] = $dish['id'];
                            }
                        }
                        $ids_str = implode(",",$ids);
                        $r = M("dish_cart")->where("id in (".$ids_str.")")->save($cart_data);
                        $result['status'] = 0;
                        $result['msg'] = "下单成功";
                        $result['id'] = $order_id;
                    }else{
                        $result['status'] = 1;
                        $result['msg'] = "下单失败";
                    }
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "购物车无商品";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "账号锁定";
        }
        echo json_encode($result);
        exit;
    }

    /*
     * 提交团购订单
     * @chenxuan
     * 2015-05-26
     */

    public function add_tuan_order() {
        $uid = $_REQUEST['uid'];   //用户ID
        $goods_id = $_REQUEST['goods_id']; //商品ID
        $amount = $_REQUEST['amount']; //数量
        $goods = M('goods')->where("id=" . $goods_id)->find();
        do {
            $order_sn = $this->get_order_sn();
            break;
        } while (check_tuan_order($order_sn) > 0);
            $order_data = array(
                'order_sn' => $order_sn,
                'user_id' => $uid,
                'total_price' => $amount * $goods['discount'],
                'order_time' => time(),
                'pay_time' => '',
                'pay_type' => '',
                'deadline' => $goods['valid_time'],
                'status' => 0
            );
            $id = M('tuan_order')->add($order_data);
            if($id){
                $order = M('tuan_order')->where('id='.$id)->find();
                $order_goods_data = array(
                    'order_id'=>$id,
                    'goods_id' => $goods_id,
                    'shop_id' => $goods['sid'],
                    'goods_name' =>$goods['name'],
                    'amount' => $amount,
                    'unit_price' => $goods['discount'],
                );
                $order_goods_id = M('tuan_order_goods')->add($order_goods_data);
                if($order_goods_id){
                    $order_goods = M('tuan_order_goods')->where("id=".$order_goods_id)->find();
                    $order['goods'] = $order_goods;
                    $results = array(
                        'status' => '00',
                        'order_id'=>$id,
                        'order'=>$order,
                        'msg' => "创建订单成功"
                    );
                }else{
                    $results = array(
                        'status' => '01',
                        'msg' => "创建订单失败"
                    );
                }
            }else{
                $results = array(
                    'status' => '01',
                    'msg' => "创建订单失败"
                );
            }
            echo json_encode($results);
            exit;
    }

    /*
     * 支付接口
     * @chenxuan
     * 2015-05-27
     */

    public function pay() {
        $order_sn = $_REQUEST['order_sn'];
        $total_fee = $_REQUEST['total_fee'];
        $merId = 483724;
        //商户系统生成的订单号
//        $random = $dealOrder = rand(0, 1000000000);
        $random = $dealOrder = $order_sn;
        //支付金额，保留两个小数位
//        $dealFee = number_format(0.01, 2);        
        $dealFee = number_format($total_fee, 2);
        //订单支付结果同步返回地址
        $dealReturn = "http://" . $_SERVER['HTTP_HOST'] . "/index.php/Api/Server/respond";
        //订单支付结果异步返回地址
        $dealNotify = "http://" . $_SERVER['HTTP_HOST'] . "/index.php/Api/Server/respond";
        //密钥授权码
        $dealKey = "pSJQnZTJP12c1FZXXaJ66rsgQj5LPlW3PsYZTsPtVkaKVLZwUViBK1uaaB2B4Vs3Spkm9EDVourw6vkI3fYQKZQX5eYQjuN50YRA0yYJx5NrM29Y7PiwVg65yfXNvrLW";
        //生成签名
        $dealSignure = sha1($merId . $dealOrder . $dealFee . $dealReturn . $dealKey);

        //获得表单传过来的数据
        $def_url = '    <form  id="alipaysubmit" name="alipaysubmit" method="post" action="http://user.sdecpay.com/paygate.html"  >';
        $def_url .= '	<input type = "hidden" name = "merId"	value = "' . $merId . '">';
        $def_url .= '	<input type = "hidden" name = "dealOrder" 				value = "' . $dealOrder . '">';
        $def_url .= '	<input type = "hidden" name = "dealFee" 			value = "' . $dealFee . '">';
        $def_url .= '	<input type = "hidden" name = "dealSignure"			value = "' . $dealSignure . '">';
        $def_url .= '	<input type = "hidden" name = "dealReturn"			value = "' . $dealReturn . '">';
        $def_url .= '	<input type = "hidden" name = "dealNotify"			value = "' . $dealNotify . '">';
        $def_url .= '   <input type="submit" value="确认" style="display:none;">';
        $def_url .= '   </form><script>document.forms["alipaysubmit"].submit();</script>';
        echo $def_url;
        exit;
    }

    public function response_wx(){
        include_once("./log_.php");
        include_once($_SERVER['DOCUMENT_ROOT']."meal/Public/wx/WxPayPubHelper/WxPayPubHelper.php");

        //使用通用通知接口
        $notify = new Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];  
        $notify->saveData($xml);
        
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        //echo $returnXml;
        $arr = $notify->xmlToArray($xml);
        
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        
        //以log文件形式记录回调信息
        $log_ = new Log_();
        $log_name="./notify_url.log";//log文件路径
        $log_->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");

        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                $log_->log_result($log_name,"【通信出错】:\n".$xml."\n");
            }
            elseif($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                $log_->log_result($log_name,"【业务出错】:\n".$xml."\n");
            }
            else{
                //此处应该更新一下订单状态，商户自行增删操作
                $log_->log_result($log_name,"【支付成功】:\n".$xml."\n");
                file_put_contents('/pay_rs.html', var_export($_GET, true), FILE_APPEND);
                file_put_contents('/pay_rs.html', var_export($arr, true), FILE_APPEND);
                //----------------------业务处理结束-------------------------------------------------------
                
            }
            
            //商户自行增加处理流程,
            //例如：更新订单状态
            //例如：数据库操作
            //例如：推送支付完成信息
            
        }
    }

    /*
     * 支付回传
     * @chenxuan
     * 2015-05-27
     */

    public function respond() {
        $dealOrder = $_REQUEST['dealOrder'];
        $dealFee = $_REQUEST['dealFee'];
        $dealState = $_REQUEST['dealState'];
        $dealSignure = $_REQUEST['dealSignure'];
        if ($dealState == 'SUCCESS') {
            if ($this->check_tuan_order($dealOrder) > 0) {
                $data = array(
                    'pay_type' => "联行支付",
                    'pay_time' => time(),
                    'status' => 1
                );
                M('tuan_order')->where("order_sn = ".$dealOrder)->save($data);
                $order_id = M('tuan_order')->where('order_sn='.$dealOrder)->getField('id');
                $res = M('tuan_order_code')->where('order_id='.$order_id)->count();
                if(!$res){
                    $amount = M('tuan_order_goods')->where('order_id='.$order_id)->getField('amount');
                    for ($i=0; $i < $amount; $i++) { 
                        do {
                            $code = $this->get_order_code();
                            break;
                        } while (check_tuan_code($code) > 0);
                        $code_data = array(
                            'order_id'=>$order_id,
                            'code'=>$code,
                            'status'=>0,
                        );
                        M('tuan_order_code')->add($code_data);
                    }
                }
                echo "notify_success";
                exit;
            }else{
                echo "notify_failed";
                exit;
            }
        } else {
            echo "notify_failed";
            exit;
        }
    }

    public function respond_cp() {
        $dealOrder = $_REQUEST ['orderId'];
        $respCode = $_REQUEST['respCode'];
        if ($respCode == '00') {
            if ($this->check_tuan_order($dealOrder) > 0) {
                $data = array(
                    'pay_type' => "银联支付",
                    'pay_time' => time(),
                    'status' => 1
                );
                M('tuan_order')->where("order_sn = ".$dealOrder)->save($data);
                $order_id = M('tuan_order')->where('order_sn='.$dealOrder)->getField('id');
                $res = M('tuan_order_code')->where('order_id='.$order_id)->count();
                $coupon_id = M("tuan_order")->where("order_id = ".$order_id)->getField("coupon_id");
                $result = M("away_order o")->join("meal_user u on (o.user_id = u.id)")->where("o.id = ".$order_id)->field("u.id as user_id,u.integral")->find();
                $integral = $result['integral'];
                $user_id = $result['user_id'];
                $total_price = M("away_order")->where("id = ".$order_id)->getField("total_price");
                $total_price = intval($total_price);
                if($total_price >= 100){
                    $integral = intval($integral) + $total_price;
                    M("user")->where("id = ".$user_id)->save(array('integral'=>$integral));
                }
                if($coupon_id){
                    M("coupon_id")->where("id=".$coupon_id)->save(array("status"=>1));
                }
                $good = M("tuan_order_goods g")->join("left join meal_goods g1 on (g.goods_id = g1.id)")->where("g.order_id = ".$order_id)->field("g.goods_id,g1.salenum")->find();
                $salenum = intval($good['salenum'])+1;
                M("goods")->where("id = ".$good['goods_id'])->save(array("salenum"=>$salenum));
                if(!$res){
                    $amount = M('tuan_order_goods')->where('order_id='.$order_id)->getField('amount');
                    for ($i=0; $i < $amount; $i++) { 
                        do {
                            $code = $this->get_order_code();
                            break;
                        } while (check_tuan_code($code) > 0);
                        $code_data = array(
                            'order_id'=>$order_id,
                            'code'=>$code,
                            'status'=>0,
                        );
                        M('tuan_order_code')->add($code_data);
                    }
                }
                echo "notify_success";
                exit;
            }else{
                if ($this->check_away_order($dealOrder) > 0) {
                    $data = array(
                        'pay_type' => "银联支付",
                        'pay_time' => time(),
                        'status' => 1
                    );
                    M('away_order')->where("order_sn = ".$dealOrder)->save($data);
                    $order_id = M('away_order')->where('order_sn='.$dealOrder)->getField('id');
                    $money_pay = M("away_order")->where("id = ".$order_id)->getField("money_pay");
                    $res = M('away_order_code')->where('order_id='.$order_id)->count();
                    $coupon_id = M("away_order")->where("order_id = ".$order_id)->getField("coupon_id");
                    $result = M("away_order o")->join("meal_user u on (o.user_id = u.id)")->where("o.id = ".$order_id)->field("u.id as user_id,u.integral")->find();
                    $integral = $result['integral'];
                    $user_id = $result['user_id'];
                    if($money_pay){
                        M("user")->where("id = ".$user_id)->save(array("money"=>0));
                    }
                    $total_price = M("away_order")->where("id = ".$order_id)->getField("total_price");
                    $total_price = intval($total_price);
                    $fanli_price = number_format(($total_price * 0.1),1);
                    $fanli_price2 = number_format(($total_price * 0.03),1);
                    $fanli_price3 = number_format(($total_price * 0.02),1);
                    $invite_id = M("user")->where("id = ".$user_id)->getField("invite_id");
                    if($invite_id){
                        $user_money = M("user")->where("id = ".$invite_id)->getField("money");
                        $user_money = floatval($user_money) + $fanli_price;
                        M("user")->where("id = ".$invite_id)->save(array("money"=>$user_money));
                        $invite_id2 = M("user")->where("id = ".$invite_id)->getField("invite_id");
                        if($invite_id2){
                            $user_money2 = M("user")->where("id = ".$invite_id2)->getField("money");
                            $user_money2 = floatval($user_money2) + $fanli_price2;
                            M("user")->where("id = ".$invite_id2)->save(array("money"=>$user_money2));
                            $invite_id3 = M("user")->where("id = ".$invite_id2)->getField("invite_id");
                            if($invite_id3){
                                $user_money3 = M("user")->where("id = ".$invite_id3)->getField("money");
                                $user_money3 = floatval($user_money3) + $fanli_price3;
                            }
                        }
                    }
                    if($total_price >= 100){
                        $integral = intval($integral) + $total_price;
                        M("user")->where("id = ".$user_id)->save(array('integral'=>$integral));
                    }
                    if($coupon_id){
                        M("coupon_id")->where("id=".$coupon_id)->save(array("status"=>1));
                    }
                    $dishes = M("away_order_goods g")->join("left join meal_shop_dishes d on (g.goods_id = d.id)")->where("g.order_id = ".$order_id)->field("g.goods_id,d.salenum")->select();
                    foreach ($dishes as $dish) {
                        $salenum = intval($dish['salenum'])+1;
                        $id = $dish['goods_id'];
                        $data = array('salenum'=>$salenum);
                        M("shop_dishes")->where("id = ".$id)->save($data);
                    }
                    if(!$res){
                        do {
                            $code = $this->get_order_code();
                            break;
                        } while (check_tuan_code($code) > 0);
                        $code_data = array(
                            'order_id'=>$order_id,
                            'code'=>$code,
                            'status'=>0,
                        );
                        M('away_order_code')->add($code_data);
                    }
                    echo "notify_success";
                    exit;
                }else{
                    echo "notify_failed";
                    exit;
                }
            }
        } else {
            echo "notify_failed";
            exit;
        }
    }

    public function respond_cp_2() {
        $order_id = $_REQUEST ['order_id'];
        $coupon_id = $_REQUEST['coupon_id'];
        $coupon = M("coupon_user u")->join("left join meal_coupon c on (u.coupon_id = c.id)")->where("u.id = ".$coupon_id." and u.status = 0")->field("c.price,c.id")->find();
        $order = M("tuan_order")->where("id = ".$order_id." and status = 0")->find();
        $result = array();
        if(floatval($order['total_price']) <= floatval($coupon['price'])){
            if($order['id']){
                $data = array(
                    'pay_type' => "红包抵用",
                    'pay_time' => time(),
                    'status' => 1,
                    'coupon_id'=>$coupon['id']
                );
                M('tuan_order')->where("id = ".$order_id)->save($data);
                $res = M('tuan_order_code')->where('order_id='.$order_id)->count();
                $good = M("tuan_order_goods g")->join("left join meal_goods g1 on (g.goods_id = g1.id)")->where("g.order_id = ".$order_id)->field("g.goods_id,g1.salenum")->find();
                $salenum = intval($good['salenum'])+1;
                M("goods")->where("id = ".$good['goods_id'])->save(array("salenum"=>$salenum));
                M("coupon_user")->where("id = ".$coupon_id)->save(array('status'=>1));
                if(!$res){
                    $amount = M('tuan_order_goods')->where('order_id='.$order_id)->getField('amount');
                    for ($i=0; $i < $amount; $i++) { 
                        do {
                            $code = $this->get_order_code();
                            break;
                        } while (check_tuan_code($code) > 0);
                        $code_data = array(
                            'order_id'=>$order_id,
                            'code'=>$code,
                            'status'=>0,
                        );
                        M('tuan_order_code')->add($code_data);
                    }
                }
                $result['status'] = 0;
                $result['msg'] = "支付成功";
            }else{
                $result['status'] = 1;
                $result['msg'] = "无此订单";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "条件不符";
        }
        echo json_encode($result);
        exit;
    }

    public function respond_cp_away() {
        $order_id = $_REQUEST ['order_id'];
        $coupon_id = $_REQUEST['coupon_id'];
        $coupon = M("coupon_user u")->join("left join meal_coupon c on (u.coupon_id = c.id)")->where("u.id = ".$coupon_id." and u.status = 0")->field("c.price,c.id")->find();
        $order = M("away_order")->where("id = ".$order_id." and status = 0")->find();
        $result = array();
        if(floatval($order['total_price']) <= floatval($coupon['price'])){
            if($order['id']){
                $data = array(
                    'pay_type' => "红包抵用",
                    'pay_time' => time(),
                    'status' => 1,
                    'coupon_id'=>$coupon['id']
                );
                $user_id = M("away_order")->where("id = ".$order_id)->getField("user_id");
                $o_count = M("away_order")->where("user_id = ".$user_id." and status > 0")->count();
                if($o_count == 0){
                    $invite_id = M("user")->where("id = ".$user_id)->getField("invite_id");
                    if($invite_id){
                        $invite_hb_data = array(
                            'coupon_id'=>7,
                            'user_id'=>$invite_id,
                            'add_time'=>time(),
                            'status'=>0,
                        );
                        M("coupon_user")->add($invite_hb_data);
                    }
                }
                M('away_order')->where("id = ".$order_id)->save($data);
                $res = M('away_order_code')->where('order_id='.$order_id)->count();
                $dishes = M("away_order_goods g")->join("left join meal_shop_dishes d on (g.goods_id = d.id)")->where("g.order_id = ".$order_id)->field("g.goods_id,d.salenum")->select();
                foreach ($dishes as $dish) {
                    $salenum = intval($dish['salenum'])+1;
                    $id = $dish['goods_id'];
                    $data = array('salenum'=>$salenum);
                    M("shop_dishes")->where("id = ".$id)->save($data);
                }
                if(!$res){
                    do {
                        $code = $this->get_order_code();
                        break;
                    } while (check_away_code($code) > 0);
                    $code_data = array(
                        'order_id'=>$order_id,
                        'code'=>$code,
                        'status'=>0,
                    );
                    M('away_order_code')->add($code_data);
                }
                $result['status'] = 0;
                $result['msg'] = "支付成功";
            }else{
                $result['status'] = 1;
                $result['msg'] = "无此订单";
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = "条件不符";
        }
        echo json_encode($result);
        exit;
    }

    public function up_money_pay(){
        $id = $_REQUEST['id'];
        $money = $_REQUEST['money'];
        $res = M("away_order")->where("id = ".$id)->save(array("money_pay"=>$money));
        $result['status'] = 0;
        $result['msg'] = "请求成功";
        echo json_encode($result);
        exit;
    }

    public function money_pay_com() {
        $id = $_REQUEST ['id'];
        $user_id = $_REQUEST['user_id'];
        $total = $_REQUEST['total'];
        $money = M("user")->where("id = ".$user_id)->getField("money");
        $result = array();
        if(floatval($money) >= floatval($total)){
            $money = floatval($money) - floatval($total);
            do {
                $code = $this->get_order_code();
                break;
            } while (check_away_code($code) > 0);
            $code_data = array(
                'order_id'=>$id,
                'code'=>$code,
                'status'=>0,
            );
            M('away_order_code')->add($code_data);
            M("user")->where("id=".$user_id)->save(array("money"=>$money));
            M("away_order")->where("id=".$id)->save(array("status"=>1,"pay_time"=>time(),"pay_type"=>"余额支付"));
            $o_count = M("away_order")->where("user_id = ".$user_id." and status > 0")->count();
            if($o_count == 0){
                $invite_id = M("user")->where("id = ".$user_id)->getField("invite_id");
                if($invite_id){
                    $invite_hb_data = array(
                        'coupon_id'=>7,
                        'user_id'=>$invite_id,
                        'add_time'=>time(),
                        'status'=>0,
                    );
                    M("coupon_user")->add($invite_hb_data);
                }
            }
            $result['status'] = 0;
            $result['msg'] = "支付成功";
        }else{
            $result['status'] = 1;
            $result['msg'] = "余额不足";
        }
        echo json_encode($result);
        exit;
    }

    public function get_order_code(){
        $code = rand(1000,9999).time();
        return $code;
    }

    public function check_tuan_code($code){
        return (M('tuan_order_code')->where('code=$code')->count());
    }
    public function check_away_code($code){
        return (M('away_order_code')->where('code=$code')->count());
    }

    /*
     * 生成优惠券
     * @chenxuan
     * 2015-05-26
     */

    function get_ticket_str() {
        $str = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randString = '';
        $len = strlen($str) - 1;
        for ($i = 0; $i < 16; $i++) {
            $num = mt_rand(0, $len);
            $randString .= $str[$num];
        }
        return $randString;
    }

    function get_invitation() {
        $str = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randString = '';
        $len = strlen($str) - 1;
        for ($i = 0; $i < 8; $i++) {
            $num = mt_rand(0, $len);
            $randString .= $str[$num];
        }
        return $randString;
    }

    function check_invitation($invitation){
        $count = M("user")->where("invitationa = '".$invitationa."'")->count();
        return $count;
    }

    /*
     * 生成订单号
     * @chenxuan
     * 2015-05-25
     */

    function get_order_sn() {
        return date('YmdHis').rand(1000,9999);
    }

    /*
     * 验证订单号唯一
     * @chenxuan
     * 2015-05-25
     */

    function check_order($order_sn) {
        return M('order')->where("ordernum = $order_sn")->count();
    }

    function check_tuan_order($order_sn) {
        return M('tuan_order')->where("order_sn = ".$order_sn)->count();
    }

    function check_vip_order($order_sn) {
        return M('vip_card_order')->where("order_sn = ".$order_sn)->count();
    }

    function check_away_order($order_sn) {
        return M('away_order')->where("order_sn = ".$order_sn)->count();
    }

    /*
     * 无限分类（树状）
     * @chenxuan
     * 2015-5-7
     */

    function generateTree($array) {
        $items = array();
        foreach ($array as $val) {
            $items[$val['id']] = $val;
            if(!$val['pid']){
                $items[$val['id']]['img'] = C('SITE_URL') . C('categoryFile') . $val['img'];
            }
        }
        $tree = array();
        foreach ($items as $key => $item) {
            if ($item['pid'] != 0) {
                $items[$item['pid']]['son'][] = &$items[$item['id']];
            } else {
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }

    /*
     * 刷单用接口
     * @阙渊
     * 2015-06-17
     */
    public function shuadan(){
        $max = $_REQUEST['max'];
        $min = $_REQUEST['min'];
        $cat = $_REQUEST['cat'];
        $cat = trim($cat);
        if($cat){
            $id = M('category')->where("name like '".$cat."%' ")->getField("id");
            if($id){
                $goods = M("goods")->where("sub_cat=".$id)->field('id,salenum')->select();
                $goods_count = M("goods")->where("sub_cat=".$id)->count();
                if($goods){
                    $i = 0;
                    foreach ($goods as $good) {
                        $count = rand($min,$max);
                        $data = array('salenum'=>$count);
                        $res = M("goods")->where('id='.$good['id'])->save($data);
                        if($res){
                            $i++;
                        }
                    }
                }
            }
            echo "【".$cat."】分类总共：".$goods_count."个商品，成功刷单了：".$i."个商品";
            exit;
        }else{
            echo "分类不可为空";
            exit;
        }
    }

    /*
     * 刷单用接口2
     * @阙渊
     * 2015-06-17
     */
    public function shuadan2(){
        $max = $_REQUEST['max'];
        $min = $_REQUEST['min'];
        if($max && $min){
            $goods = M("goods")->where("salenum = 0")->field('id,salenum')->select();
            if($goods){
                $i = 0;
                foreach ($goods as $good) {
                    $count = rand($min,$max);
                    $data = array('salenum'=>$count);
                    $res = M("goods")->where('id='.$good['id'])->save($data);
                    if($res){
                        $i++;
                    }
                }
            }
        }
        echo "成功刷单了：".$i."个商品";
        exit;
    }

    public function dish_recommend(){
        $id = $_REQUEST['id'];
        $dish = M("shop_dishes")->where("id = ".$id)->field("shop_id,labelid")->find();
        $shop_id = $dish['shop_id'];
        $labelid = $dish['labelid'];
        $list = M("shop_dishes d")->join("left join meal_dish_unit u on (d.unitid = u.id)")->where("d.id != ".$id." and d.status = 1 and d.shop_id = ".$shop_id)->order("d.salenum desc,d.ord desc")->limit(0,5)->field("d.id,d.shop_id,d.name,d.price,d.salenum,d.img,d.intro,d.amount,u.name as unit")->select();
        $result['status'] = 0;
        $result['msg'] = '请求成功';
        $result['list'] = $list;
        echo json_encode($result);
        exit;
    }

    public function dish_detail(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $dish = M("shop_dishes d")->join("left join meal_dish_unit u on (d.unitid = u.id) left join meal_dish_gg g on (g.dish_id = d.id)")->where("d.id = ".$id." and g.status = 1")->order("ord desc")->field("max(g.price) as max,max(g.price_tuan) as max_tuan,min(g.price) as min,min(g.price_tuan) as min_tuan,d.id,d.detail_img,d.shop_id,d.name,d.price,d.salenum,d.img,d.intro,d.amount,u.name as unit,d.is_out,d.img")->find();
        $dish['count'] = M("dish_cart")->where("dish_id = ".$id." and user_id = ".$user_id." and status = 0")->getField("amount");
        if(!$dish['count']){
            $dish['count'] = 0;
        }
        $result = array();
        if($dish){
            $result['status'] = 0;
            $result['msg'] = '请求成功';
            $result['dish'] = $dish;
        }else{
            $result['status'] = 1;
            $result['msg'] = '无此产品';
        }
        echo json_encode($result);
        exit;
    }

    public function active_dish_detail(){
        $id = $_REQUEST['id'];
        $dish = M("shop_dishes d")->join("left join meal_dish_unit u on (d.unitid = u.id)")->where("d.id = ".$id."")->field("d.id,d.detail_img,d.shop_id,d.name,d.active_price,d.active_num,d.active_max_num,d.active_gg,d.salenum,d.img,d.intro,d.amount,u.name as unit,d.is_out,d.img")->find();
        $result = array();
        if($dish){
            $result['status'] = 0;
            $result['msg'] = '请求成功';
            $result['dish'] = $dish;
        }else{
            $result['status'] = 1;
            $result['msg'] = '无此产品';
        }
        echo json_encode($result);
        exit;
    }

    public function getGgPrice(){
        $id = $_REQUEST['id'];
        $price = M("dish_gg")->where("id = ".$id." and status = 1")->getField("price");
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'price'=>$price,
        );
        echo json_encode($result);
        exit;
    }

    public function dish_gg(){
        $id = $_REQUEST['id'];
        $ggs = M("dish_gg")->where("dish_id = ".$id." and status = 1 and is_tuan = 0 and active_id = 0")->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'ggs'=>$ggs,
        );
        echo json_encode($result);
        exit;
    }

    public function dish_gg_tuan(){
        $id = $_REQUEST["id"];
        $gg = M("dish_gg")->where("dish_id = ".$id." and status = 1 and is_tuan = 1")->find();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'gg'=>$gg,
        );
        echo json_encode($result);
        exit;
    }

    public function get_adds(){
        $city_id = $_REQUEST["city_id"];
        $type = $_REQUEST["type"];
        $type_arr = explode(",",$type);
        $result = array();
        if(!$city_id || !$type){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            if(count($type_arr) == 1){
                $adds = M("add")->where("city_id = ".$city_id." and type = ".$type." and status = 1")->order("ord desc")->select();
            }else{
                $adds = array();
                foreach ($type_arr as $t) {
                    $adds['type_'.$t] = M("add")->where("city_id = ".$city_id." and type = ".$t." and status = 1")->order("ord desc")->select();
                }
            }
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['adds'] = $adds;
        }
        echo json_encode($result);
        exit;
    }

    public function get_adds2(){
        $city_id = $_REQUEST["city_id"];
        $type = $_REQUEST["type"];
        $id_fruit = $_REQUEST['id_fruit'];
        $id_veg = $_REQUEST['id_veg'];
        $type_arr = explode(",",$type);
        $result = array();
        if(!$city_id || !$type){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            if(count($type_arr) == 1){
                $adds = M("add d")->join("left join meal_shop_dishes s on (d.dish_id = s.id)")->where("d.city_id = ".$city_id." and s.shop_id in (".$id_fruit.",".$id_veg.") and d.type = ".$type." and d.status = 1")->field("d.id,d.img,d.url,d.type,d.ord,d.dish_id,d.is_dish,d.status,d.city_id,d.is_active")->order("d.ord desc")->select();
            }else{
                $adds = array();
                foreach ($type_arr as $t) {
                    $adds['type_'.$t] = M("add d")->join("left join meal_shop_dishes s on (d.dish_id = s.id)")->where("d.city_id = ".$city_id." and s.shop_id in (".$id_fruit.",".$id_veg.") and d.type = ".$t." and d.status = 1")->field("d.id,d.img,d.url,d.type,d.ord,d.dish_id,d.is_dish,d.status,d.city_id,d.is_active")->order("d.ord desc")->select();
                }
            }
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['adds'] = $adds;
        }
        echo json_encode($result);
        exit;
    }

    public function dishes(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $shop = M("shop")->where("id=".$id)->field("id,name,logo,intro")->find();
        $labels = M("shop_dishes d")->join("left join meal_category_label l on (d.labelid = l.id)")->field("distinct d.labelid,l.name")->where("d.shop_id=".$id." and d.status = 1")->group("d.labelid")->order("l.ord desc")->select();
        if($user_id){
            $res2 = M("dish_cart")->field("sum(amount*unit_price) as total_price")->where("user_id = ".$user_id." and status = 0")->find();
            if($res2['total_price']){
                $shop['total_price'] = $res2['total_price'];
            }else{
                $shop['total_price'] = 0.00;
            }
        }else{
            $shop['total_price'] = 0.00;
        }
        foreach($labels as &$label){
            $sql = "d.shop_id=".$id." and d.labelid=".$label['labelid']." and d.status = 1";
            $label['dishes'] = M("shop_dishes d")->join("left join meal_dish_unit u on (d.unitid = u.id)")->where($sql)->order("d.ord desc")->field("d.id,d.shop_id,d.name,d.price,d.salenum,d.img,d.intro,d.amount,u.name as unit")->select();
            if($user_id){
                foreach ($label['dishes'] as &$dish) {
                    $dish['count'] = M("dish_cart")->where("dish_id = ".$dish['id']." and user_id = ".$user_id." and status = 0")->getField("amount");
                    if(!$dish['count']){
                        $dish['count'] = 0;
                    }
                }
            }else{
                foreach ($label['dishes'] as &$dish) {
                    $dish['count'] = 0;
                }
            }
        }
        $shop['labels'] = $labels;
        echo json_encode($shop);
        exit;
    }

    public function dishes2(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $shop = M("shop")->where("id=".$id)->field("id,name,logo,intro")->find();
        $labels = M("shop_dishes d")->join("left join meal_category_label l on (d.labelid = l.id)")->field("distinct d.labelid,l.name")->where("d.shop_id=".$id." and d.status = 1")->group("d.labelid")->order("l.ord desc")->select();
        if($user_id){
            $res2 = M("dish_cart")->field("sum(amount*unit_price) as total_price")->where("user_id = ".$user_id." and status = 0")->find();
            if($res2['total_price']){
                $shop['total_price'] = $res2['total_price'];
            }else{
                $shop['total_price'] = 0.00;
            }
        }else{
            $shop['total_price'] = 0.00;
        }
        foreach($labels as &$label){
            $sql = "d.shop_id=".$id." and d.labelid=".$label['labelid']." and d.status = 1 and d.is_show = 1 and u.status = 1";
            $label['dishes'] = M("shop_dishes d")->join("left join meal_dish_gg u on (u.dish_id = d.id)")->where($sql)->order("d.ord desc")->field("d.id,d.shop_id,d.name,min(u.price) as price,min(u.price) as min,max(u.price) as max,d.img,d.is_out")->group("d.id")->select();
        }
        $shop['labels'] = $labels;
        echo json_encode($shop);
        exit;
    }

    public function getDishes(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $label_id = $_REQUEST['label_id'];
        $startrow = $_REQUEST['startrow'];
        $pagesize = 10;
        $sql = "d.shop_id = ".$id." and d.status = 1 and d.is_show = 1";
        if($label_id){
            $sql .= " and d.labelid = ".$label_id;
        }
        if(!$startrow){
            $startrow = 0;
        }
        $count = M("shop_dishes d")->where($sql)->count();
        $num = ceil($count / $pagesize);
        if($startrow >= $num){
            $startrow = $num - 1;
        }
        if($startrow < 0){
            $startrow = 0;
        }
        $limit = $startrow * $pagesize;
        $sql .= " and g.status = 1";
        $result = array();
        $dishes = M("shop_dishes d")->join("left join meal_dish_gg g on (g.dish_id = d.id) left join meal_dish_unit u on (d.unitid = u.id)")->where($sql)->field("d.id,d.name,min(g.unit_price) as price,d.img,d.is_out,d.intro,u.name as unit")->group("d.id")->limit($limit,$pagesize)->order("d.ord desc,d.createtime desc")->select();
        if($dishes){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['dishes'] = $dishes;
            $result['num'] = $num;
            $result['startrow'] = $startrow;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无结果";
        }
        echo json_encode($result);
        exit;
    }

    public function getDishes2(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $label_id = $_REQUEST['label_id'];
        $pagesize = 10;
        $sql = "d.shop_id in (".$id.") and d.status = 1 and d.is_show = 1";
        if($label_id){
            $sql .= " and d.labelid = ".$label_id;
        }
        $sql .= " and g.status = 1";
        $result = array();
        $dishes = M("shop_dishes d")->join("left join meal_dish_gg g on (g.dish_id = d.id) left join meal_dish_unit u on (d.unitid = u.id)")->where($sql)->field("d.shop_id,d.id,d.name,min(g.unit_price) as price,d.img,d.is_out,d.intro,u.name as unit")->group("d.id")->order("d.ord desc,d.createtime desc")->select();
        if($dishes){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['dishes'] = $dishes;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无结果";
        }
        echo json_encode($result);
        exit;
    }

    public function getActiveDishes(){
        $id = $_REQUEST['id'];
        $pagesize = 10;
        $sql = "d.shop_id in (".$id.") and d.status = 1 and d.is_show = 1 and d.is_active = 1";
        if($label_id){
            $sql .= " and d.labelid = ".$label_id;
        }
        $result = array();
        $dishes = M("shop_dishes d")->join("left join meal_dish_unit u on (d.unitid = u.id)")->where($sql)->field("d.id,d.name,round((d.active_price/d.active_num),2) as price,d.img,d.is_out,u.name as unit,d.is_active")->order("d.ord desc")->select();
        if($dishes){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['dishes'] = $dishes;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无结果";
        }
        echo json_encode($result);
        exit;
    }

    public function getActiveDishes2(){
        $id = $_REQUEST['id'];
        $startrow = $_REQUEST['startrow'];
        $sql = "d.shop_id = ".$id." and d.status = 1 and d.is_show = 1 and d.is_active = 1";
        $pagesize = 10;
        if(!$startrow){
            $startrow = 0;
        }
        $count = M("shop_dishes d")->where($sql)->count();
        $num = ceil($count / $pagesize);
        if($startrow >= $num){
            $startrow = $num - 1;
        }
        if($startrow < 0){
            $startrow = 0;
        }
        $limit = $startrow * $pagesize;
        $result = array();
        $dishes = M("shop_dishes d")->join("left join meal_dish_unit u on (d.unitid = u.id)")->where($sql)->field("d.id,d.name,d.active_price as price,d.img,d.is_out,u.name as unit")->limit($limit,$pagesize)->order("d.ord desc")->select();
        if($dishes){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['dishes'] = $dishes;
            $result['num'] = $num;
            $result['startrow'] = $startrow;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无结果";
        }
        echo json_encode($result);
        exit;
    }

    public function getDishCate(){
        $result = array();
        $cate_id = $_REQUEST['cate_id'];
        $shop_id = $_REQUEST['shop_id'];
        if(!$cate_id){
            $cates = M("category c")->join("left join meal_category_label l on (l.sub_cat = c.id) left join meal_shop_dishes d on (d.labelid = l.id)")->where("d.shop_id in (".$shop_id.") and d.status = 1")->field("distinct c.id,c.name")->group("c.id,c.name")->select();
        }else{
            $cates = M("category_label l")->join("left join meal_shop_dishes d on (d.labelid = l.id)")->where("l.sub_cat = ".$cate_id." and d.shop_id in (".$shop_id.") and d.status = 1")->group("l.id")->order("l.ord desc")->field("distinct l.id,l.name,count(d.id) as count")->select();
        }
        if($cates){
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['cates'] = $cates;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无分类";
        }
        echo json_encode($result);
        exit;
    }

    public function get_shop_dishes(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $shop = M("shop")->where("id=".$id)->field("id,name,logo,intro")->find();
        $labels = M("shop_dishes d")->join("left join meal_category_label l on (d.labelid = l.id)")->field("distinct d.labelid,l.name")->where("d.shop_id=".$id." and d.status = 1")->group("d.labelid")->order("l.ord desc")->select();
        if($user_id){
            $res2 = M("dish_cart")->field("sum(amount*unit_price) as total_price")->where("user_id = ".$user_id." and status = 0")->find();
            if($res2['total_price']){
                $shop['total_price'] = $res2['total_price'];
            }else{
                $shop['total_price'] = 0.00;
            }
        }else{
            $shop['total_price'] = 0.00;
        }
        foreach($labels as &$label){
            $sql = "d.shop_id=".$id." and d.labelid=".$label['labelid']." and d.status = 1 and d.is_show = 1";
            $label['dishes'] = M("shop_dishes d")->join("left join meal_dish_gg u on (u.dish_id = d.id)")->where($sql)->order("d.ord desc")->field("d.id,d.shop_id,d.name,min(u.price) as price,d.img,d.is_out")->order("d.ord desc")->limit(0,4)->group("d.id")->select();
        }
        $shop['labels'] = $labels;
        echo json_encode($shop);
        exit;
    }

    public function dishes_gg(){
        $id = $_REQUEST['id'];
        $sql = "shop_id=".$id." and labelid = 18 and status = 1 and is_show = 0 and is_hot = 1";
        $dishes = M("shop_dishes")->where($sql)->order("ord desc")->field("id,shop_id,img")->select();
        $result = array(
            'status'=>0,
            'msg'=>"请求成功",
            'dishes'=>$dishes,
        );
        echo json_encode($result);
        exit;
    }

    public function ad_dishes(){
        $id = $_REQUEST['id'];
        $dishes = M("shop_dishes")->where("labelid = ".$id." and shop_id = 4122 and status = 1")->order("ord desc")->select();
        $result = array();
        if($dishes){
            $result['status'] = 0;
            $result['msg'] = '请求成功';
            $result['dishes'] = $dishes;
        }else{
            $result['status'] = 1;
            $result['msg'] = '无结果';
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取贵宾卡种类列表
     * @queyuan
     * 2016/4/7
     */
    public function vip_card_types(){
        $list = M("vip_card_type")->where("status = 1")->order("ord desc")->select();
        echo M("vip_card_type")->getLastSql();
        exit;
        $result = array(
            'status'=>0,
            'msg'=>'请求成功',
            'list'=>$list,
        );
        echo json_encode($result);
        exit;
    }

    /**
     * 获取贵宾卡种类详情
     * @queyuan
     * 2016/4/7
     */
    public function type_detail(){
        $type = $_REQUEST['type'];
        $list = M("vip_card_type")->where("type = ".$type)->order("ord desc")->select();
        $result = array(
            'status'=>0,
            'msg'=>'请求成功',
            'list'=>$list,
        );
        echo json_encode($result);
        exit;
    }

    /**
     * 添加贵宾卡订单（重复的订单直接不生成）
     * @queyuan
     * 2016/04/08
     * @param id——卡类型ID
     * @param user_id——用户ID
     */
    public function add_vip_order(){
        $id = $_REQUEST['id'];
        $user_id = $_REQUEST['user_id'];
        $result = array();
        if(!$id || !$user_id){
            $result['status'] = 1;
            $result['msg'] = "数据错误";
        }else{
            $order = M("vip_card_order")->where("user_id = ".$user_id." and card_id = ".$id." and status = 0")->find();
            if($order){
                M("vip_card_order")->where("id = ".$order['id'])->save(array('order_time'=>time()));
                $result['status'] = 0;
                $result['msg'] = "请求成功";
                $result['order'] = $order;
            }else{
                $card = M("vip_card_type")->where("id = ".$id." and status = 1")->find();
                if($card){
                    do {
                        $order_sn = $this->get_order_sn();
                        break;
                    } while (check_away_order($order_sn) > 0);
                    $data = array(
                        'order_sn'=>$order_sn,
                        'user_id'=>$user_id,
                        'card_id'=>$id,
                        'total_price'=>$card['value'],
                        'order_time'=>time(),
                        'status'=>0,
                    );
                    $res = M("vip_card_order")->add($data);
                    $order_new = M("vip_card_order")->where("user_id = ".$user_id." and card_id = ".$id." and status = 0")->find();
                    if($res){
                        $result['status'] = 0;
                        $result['msg'] = "请求成功";
                        $result['order'] = $order_new;
                    }else{
                        $result['status'] = 1;
                        $result['msg'] = "下单失败";
                    }
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "VIP卡不存在";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取VIP卡订单详情
     * @queyuan
     * 2016/04/08
     * @param id——订单ID
     */
    public function get_vip_order(){
        $id = $_REQUEST['id'];
        $result = array();
        $order = M("vip_card_order o")->join("left join meal_vip_card_type t on (o.card_id = t.id)")->where("o.id = ".$id." and o.status = 0")->field("t.name,t.type,o.memo,o.order_sn,o.total_price,o.order_time,o.status,o.phone,o.address,o.realname,o.circles,o.id,o.order_time")->find();
        if($order){
            if($order['circles']){
                $c_array = explode(",",$order['circles']);
                $cs = array();
                foreach ($c_array as $c) {
                    $cs[] = M("area")->where("id = ".$c)->getField("name");
                }
                $order['circles'] = implode(" ",$cs);
            }
            $order['s'] = strlen($order['order_sn']);
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['order'] = $order;
        }else{
            $result['status'] = 1;
            $result['msg'] = "订单不存在";
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取贵宾卡订单的收货信息
     * @queyuan
     * 2016/04/08
     * @param id——订单ID
     */
    public function get_vip_order_receive(){
        $id = $_REQUEST['id'];
        $receive = M("vip_card_order")->where("id = ".$id)->field("address,phone,circles,realname")->find();
        $result = array();
        if($receive){
            if($receive['circles']){
                $c_array = explode(",",$receive['circles']);
                $receive['pid'] = $c_array[0];
                $receive['cid'] = $c_array[1];
                $receive['aid'] = $c_array[2];
            }
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['receive'] = $receive;
        }else{
            $result['status'] = 1;
            $result['msg'] = "无此订单";
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 为贵宾卡订单添加收获地址
     * @queyuan
     * 2016/04/08
     * @param oid——订单ID
     * @param realname——真实姓名
     * @param phone——联系电话
     * @param address——具体地址
     * @param circles——区域
     */
    public function add_vip_order_receive(){
        $oid = $_REQUEST['oid'];
        $realname = $_REQUEST['realname'];
        $phone = $_REQUEST['phone'];
        $address = $_REQUEST['address'];
        $circles = $_REQUEST['circles'];
        $result = array();
        if(!$oid || !$realname || !$phone || !$address || !$circles){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $data = array(
                'realname'=>$realname,
                'phone'=>$phone,
                'address'=>$address,
                'circles'=>$circles,
            );
            $res = M("vip_card_order")->where("id = ".$oid)->save($data);
            if($res){
                $result['status'] = 0;
                $result['msg'] = "请求成功";
            }else{
                $result['status'] = 1;
                $result['msg'] = "保存失败";
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 绑定贵宾卡
     * @queyuan
     * 2016/04/08
     * @param user_id——用户ID
     * @param card_num——卡号
     * @param address——详细地址
     * @param realname——真实姓名
     * @param circles——区域字符串
     * @param phone——联系手机号
     */
    public function bind_vip_card(){
        $user_id = $_REQUEST['user_id'];
        $card_num = $_REQUEST['card_num'];
        $address = $_REQUEST['address'];
        $realname = $_REQUEST['realname'];
        $circles = $_REQUEST['circles'];
        $phone = $_REQUEST['phone'];
        $result = array();
        if(!$user_id || !$card_num || !$address || !$realname || !$circles || !$phone){
            $result['status'] = 1;
            $result['msg'] = "参数异常";
        }else{
            $card = M("vip_card")->where("card_num = '".$card_num."' and status = 1")->find();
            if($card){
                $type = M("vip_card c")->join("left join meal_vip_card_type t on (c.typeid = t.id)")->where("c.id = ".$card['id'])->getField("t.type");
                if($type == 1){
                    $validity_time = strtotime("+1 years");
                }elseif($type == 2){
                    $validity_time = strtotime("+6 months");
                }elseif($type == 3){
                    $validity_time = strtotime("+3 months");
                }elseif($type == 4){
                    $validity_time = strtotime("+1 months");
                }elseif($type == 5){
                    $validity_time = strtotime("+7 days");
                }
                $data = array(
                    'user_id'=>$user_id,
                    'realname'=>$realname,
                    'address'=>$address,
                    'phone'=>$phone,
                    'circles'=>$circles,
                    'active_time'=>time(),
                    'status'=>2,
                    'validity_time'=>$validity_time,
                );
                $res = M("vip_card")->where("id = ".$card['id'])->save($data);
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "绑定成功";
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "绑定失败";
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = "卡号有误";
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 获取用户贵宾卡信息
     * @queyuan
     * 2016/04/08
     * @param user_id——用户ID
     */
    public function user_vip_card(){
        $user_id = $_REQUEST['user_id'];
        $card = M("vip_card c")->join("left join meal_vip_card_type t on (c.typeid = t.id)")->where("c.user_id = ".$user_id." and c.status = 2")->field("c.id,c.card_num,c.times,c.active_time,c.validity_time,c.status,t.name,t.type,t.cate_ids,c.realname,c.phone,c.circles,c.address,c.typeid")->find();
        $result = array();
        if(!$card){
            $result['status'] = 1;
            $result['msg'] = "暂无贵宾卡";
        }else{
            $cs_array = explode(",",$card['circles']);
            $cs = array();
            $city_id = $cs_array[1];
            foreach ($cs_array as $c) {
                $cs[] = M("area")->where("id = ".$c)->getField("name");
            }
            $card['circles'] = implode(" ",$cs);
            $card['cates'] = M("vip_card_type_cates")->where("type_id = ".$card['typeid']." and status = 1")->order("ord desc")->select();
            foreach ($card['cates'] as &$cate) {
                if($cate['cates']){
                    $cate['dishes'] = M("shop_dishes d")->join("left join meal_category_label l on (d.labelid = l.id) left join meal_shop s on (d.shop_id = s.id)")->where("l.sub_cat in (".$cate['cates'].") and d.status = 1 and s.circles like '%,".$city_id.",%'")->order("l.sub_cat desc,d.labelid desc,d.ord desc,d.labelid asc")->field("d.*")->select();
                }
            }
            $result['status'] = 0;
            $result['msg'] = "请求成功";
            $result['card'] = $card;
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 贵宾卡用户选择喜好产品
     * @queuyan
     * 2016/04/13
     * @param id——贵宾卡ID
     * @param choose——所选择的产品ID（以','隔开）
     */
    public function vip_choose_dishes(){
        $id = $_REQUEST['id'];
        $choose = $_REQUEST['choose'];
        $is_send = $_REQUEST['is_send'];
        $memo = $_REQUEST['memo'];
        $result = array();
        if(!$id || ($is_send && !$choose) || (!$is_send && !$memo)){
            $result['status'] = 0;
            $result['msg'] = "参数错误";
        }else{
            $record = M("vip_like")->where("card_id = ".$id)->order("addtime desc")->find();
            $min = time() - intval($record['addtime']);
            $min = $min / 3600 / 24;
            if($min < 1){
                $result['status'] = 1;
                $result['msg'] = "请一小时后再试";
            }else{
                $data = array(
                    'card_id'=>$id,
                    'ids'=>$choose,
                    'addtime'=>time(),
                    'is_send'=>$is_send,
                    'memo'=>$memo,
                );
                $res = M("vip_like")->add($data);
                if($res){
                    $result['status'] = 0;
                    $result['msg'] = "请求成功";
                }else{
                    $result['status'] = 1;
                    $result['msg'] = "请求失败";
                }
            }
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 检验贵宾卡是否已经选择过配送产品
     * @queyuan
     * 2016/05/10
     * @param user_id——用户ID
     */
    public function check_choose_dishes(){
        $user_id = $_REQUEST['user_id'];
        $like = M("vip_like l")->join("left join meal_vip_card c on (l.card_id = c.id)")->where("l.status = 0 and c.user_id = ".$user_id)->find();
        $result = array();
        if($like){
            $result['status'] = 1;
            $result['msg'] = "已选购";
        }else{
            $result['status'] = 0;
            $result['msg'] = "为选购";
        }
        echo json_encode($result);
        exit;
    }
}
?>
